Springboot 引入 Redis 并配置序列化并封装RedisTemplate

2022-11-13 17:11:17 配置 引入 封装

前言

为什么要配置序列化:如果不配置序列化的话,我们在redis数据库中存储的数据可能以乱码形式显示出来,不方便我们判断数据存储的正确性,说白了就是序列化以后存进去的是什么,查询出来的就是什么,否则我们的键值都会变成一串看不懂的乱码。

为什么要封装RedisTemplate,因为如果不进行封装的话,大家请看,是不是有黄色的警告信息,看着起来很不舒服,RedisTemplate后面的尖括号可以填泛型,填写以后警告就消失了,但我们的类型很多,每次只能Autowired一个RedisTemplate,所以不能写尖括号内的类型,同时封装也能按照自己的习惯自定义方法,更好用。

一、引入依赖

只需要引入这一个就可以了,现在的版本里面包含了 lettuce ,所以不需要再额外引入 common-pool2

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

二、配置yml

因为我使用的是SpringBoot 3.0,所以配置层级是 spring-data-redis,如果你们的配置文件爆红,说明你们是旧版,那么把data去掉就可以了,直接是 spring-redis

server:
  port: 8081
spring:
  data:
    redis:
      #数据库索引
      database: 0
      #redis 服务器地址
      host: 127.0.0.1
      #redis 端口
      port: 6379
      #redis 密码 默认为空
      passWord:
      # 链接超时时间
      connect-timeout: 10s
      #lettuce连接池配置
      lettuce:
        pool:
          # 链接池中最小的空闲链接 默认为0
          min-idle: 0
          # 链接池中最大的空闲连接 默认为 8
          max-idle: 8
          #连接池中最大数据库链接数 默认为8
          max-active: 8
          #连接池最大阻塞等待时间 负值表示没有限制
          max-wait: -1ms

三、封装RedisTemplate

注意:我这里用的是 Java17 新增的 record 纪录类,如果你们是低版本的 jdk ,把 record 更换成 class ,然后注入RedisTemplate

package com.xuyijie.redisdemo.utils;

import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@Component
public record RedisUtil<K, V>(RedisTemplate<K, V> redisTemplate) {

    
    @SuppressWarnings("all")
    public RedisUtil {
    }

    
    private static final long DEFAULT_EXPIRE_TIME = 60 * 60 * 48;

    
    public long getExpireTime(K key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    
    public void setExpireTime(K key, long expireTime) {
        try {
            if (expireTime > 0) {
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    public void removeExpireTime(K key) {
        redisTemplate.boundValueOps(key).persist();
    }

    
    public Set<K> keys(K key) {
        return redisTemplate.keys(key);
    }

    
    public boolean hasKey(K key) {
        try {
            return Boolean.TRUE.equals(redisTemplate.hasKey(key));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public void delete(Collection<K> keys) {
        redisTemplate.delete(keys);
    }

    
    @SuppressWarnings("unchecked")
    public Boolean setNx(String key, String value, long expire) {
        return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
            Boolean acquire = connection.setNX(key.getBytes(), value.getBytes());
            connection.expire(key.getBytes(), expire);
            return acquire;
        });
    }

    
    
    public void set(K key, V value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    public void set(K key, V value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                redisTemplate.opsForValue().set(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    @SuppressWarnings("unchecked")
    public Long incrBy(String key, long number) {
        return (Long) redisTemplate.execute((RedisCallback) connection
                -> connection.incrBy(key.getBytes(), number));
    }

    
    @SuppressWarnings("unchecked")
    public Long decrBy(String key, long number) {
        return (Long) redisTemplate.execute((RedisCallback) connection
                -> connection.decrBy(key.getBytes(), number));
    }

    
    public Object get(K key) {
        BoundValueOperations<K, V> boundValueOperations = redisTemplate.boundValueOps(key);
        return boundValueOperations.get();
    }

    

    
    public void listRightPush(K key, V value) {
        ListOperations<K, V> listOperations = redisTemplate.opsForList();
        //从队列右插入
        listOperations.rightPush(key, value);
    }

    
    public void listLeftPush(K key, V value) {
        ListOperations<K, V> listOperations = redisTemplate.opsForList();
        //从队列右插入
        listOperations.leftPush(key, value);
    }

    
    public void listRightPushAll(K key, List<V> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    public void listLeftPushAll(K key, List<V> value) {
        try {
            redisTemplate.opsForList().leftPushAll(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    public Object listGetWithIndex(K key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    
    public V listLeftPop(K key) {
        ListOperations<K, V> listOperations = redisTemplate.opsForList();
        return listOperations.leftPop(key);
    }

    
    public V listRightPop(K key) {
        ListOperations<K, V> listOperations = redisTemplate.opsForList();
        return listOperations.rightPop(key);
    }

    
    public List<V> listRange(K key, long start, long end) {
        try {
            ListOperations<K, V> listOperations = redisTemplate.opsForList();
            return listOperations.range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    
    public long listSize(K key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    
    public void listSet(K key, long index, V value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    public long listRemove(K key, long count, V value) {
        try {
            return redisTemplate.opsForList().remove(key, count, value);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    

    
    public Object hashGet(K key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    
    public Map<Object, Object> hashMGet(K key) {
        return redisTemplate.opsForHash().entries(key);
    }

    
    public void hashMSet(K key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    public void hashMSet(K key, Map<String, Object> map, long expireTime) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (expireTime > 0) {
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    public <HK, HV> void hashPut(K key, HK hKey, HV value) {
        try {
            HashOperations<K, HK, HV> hashOperations = redisTemplate.opsForHash();
            hashOperations.put(key, hKey, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    public <HK, HV> void hashPut(K key, HK hKey, HV value, long expireTime) {
        try {
            redisTemplate.opsForHash().put(key, hKey, value);
            if (expireTime > 0) {
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    public <HK, HV> boolean hashHasKey(K key, HK hKey) {
        HashOperations<K, HK, HV> hashOperations = redisTemplate.opsForHash();
        return hashOperations.hasKey(key, hKey);
    }

    
    public <HK, HV> List<HV> hashValues(K key) {
        HashOperations<K, HK, HV> hashOperations = redisTemplate.opsForHash();
        return hashOperations.values(key);
    }

    
    public <HK, HV> Set<HK> hashHKeys(K key) {
        HashOperations<K, HK, HV> hashOperations = redisTemplate.opsForHash();
        return hashOperations.keys(key);
    }

    
    public <HK, HV> Long hashDelete(K key, Object... hashKeys) {
        HashOperations<K, HK, HV> hashOperations = redisTemplate.opsForHash();
        return hashOperations.delete(key, hashKeys);
    }

    
    
    public void setAdd(K key, V... values) {
        redisTemplate.opsForSet().add(key, values);
    }

    
    public void setAdd(K key, long expireTime, V... values) {
        redisTemplate.opsForSet().add(key, values);
        if (expireTime > 0) {
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
        }
    }

    
    public long setSize(K key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    
    public Set<V> setValues(K key) {
        SetOperations<K, V> setOperations = redisTemplate.opsForSet();
        return setOperations.members(key);
    }

    
    public boolean setHasKey(K key, V value) {
        return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, value));
    }

    
    public Long setDelete(K key, Object... value) {
        SetOperations<K, V> setOperations = redisTemplate.opsForSet();
        return setOperations.remove(key, value);
    }

    
    
    public void zSetAdd(K key, V value, long score) {
        ZSetOperations<K, V> zSetOperations = redisTemplate.opsForZSet();
        zSetOperations.add(key, value, score);
    }

    
    public Set<V> zSetValuesRange(K key, long score1, long score2) {
        ZSetOperations<K, V> zSetOperations = redisTemplate.opsForZSet();
        return zSetOperations.range(key, score1, score2);
    }

    
    public Long zSetDeleteByValue(K key, Object... value) {
        ZSetOperations<K, V> zSetOperations = redisTemplate.opsForZSet();
        return zSetOperations.remove(key, value);
    }

    
    public Long zSetDeleteRange(K key, long size1, long size2) {
        ZSetOperations<K, V> zSetOperations = redisTemplate.opsForZSet();
        return zSetOperations.removeRange(key, size1, size2);
    }

    
    public Long zSetDeleteByScore(K key, long score1, long score2) {
        ZSetOperations<K, V> zSetOperations = redisTemplate.opsForZSet();
        return zSetOperations.removeRangeByScore(key, score1, score2);
    }

}

当然有些同学已经发现了,我这样封装,也没有解决RedisUtil后面的尖括号不输入内容出现警告的问题,因为我是业务需要,所以保留了尖括号指定类型

在这里插入图片描述

你们如果非不想输入尖括号内的类型,这样改,把RedisUti和RedisTemplate的尖括号去掉,下面的方法中的 K 全部改为 String,V 全部改为 Object就可以了

@Component
public record RedisUtil(RedisTemplate redisTemplate) {

    @SuppressWarnings("all")
    public RedisUtil {
    }

    
    private static final long DEFAULT_EXPIRE_TIME = 60 * 60 * 48;

    
    public long getExpireTime(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

四、controller使用RedisUtil

package com.xuyijie.redisdemo.controller;

import com.xuyijie.redisdemo.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.WEB.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private RedisUtil<String, String> redisUtil;

    @GetMapping("/helloString/{key}")
    public String helloString(@PathVariable String key){
        redisUtil.set("key", key);
        return (String) redisUtil.get("key");
    }

    @GetMapping("/helloList")
    public List<String> helloList(){
        //向key中push一个元素“0”
        redisUtil.listLeftPush("key2", "0");
        //把一个列表push进key
        List<String> list = new ArrayList<>(Arrays.asList("1", "2"));
        redisUtil.listLeftPushAll("key2", list);
        //读取存储的列表中的全部元素,0, -1代表从第一个元素到最后一个元素
        return redisUtil.listRange("key2", 0, -1);
    }

}

五、操作演示

我们先来演示一下第二个方法,直接浏览器请求,可以看到,存入并查询出了我们存入的数据

redis控制台也能查询出来

为什么先演示第二个方法呢,因为要用第一个向你们展示一个“小错误”,我们输入中文来测试一下

很棒,成功存入并正确读取出来了对不对
那我们去控制台看一看,注意看,我们的键还是“key”,没有乱码,value的前半部分中文乱码,后面的String是正常显示的,说明这不是序列化的问题

解决方案是,使用 redis-cli --raw 进入控制台,flushall 先清空数据,再次请求接口存储数据,查询出来的中文就出来了,但是我们还是看不懂,这和代码和redis没有关系

原因是电脑的 cmd 字符默认是 GBK,你们bing一下,看看怎么把cmd改为 UTF-8,好像要从注册表里面改,改好就可以正确显示了

其实代码可以正确读取出来就说明一切正常的了,我们控制台看到乱码不必理会,这里只是提一下

到此这篇关于Springboot 引入 Redis 并配置序列化并封装RedisTemplate 的文章就介绍到这了,更多相关Springboot 引入 Redis 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章