SpringBoot 2.x 整合 Redis

整合

1)添加依赖

XML 复制代码
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 如果没有使用下面给出的工具类,那么就不需要引入 -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.2.4</version>
</dependency>

2)application.xml 配置

spring:
  redis:
    database: 0
    # ip 或者域名
    host: 192.168.224.128
    # 密码
    password: TO6Md91Advf
    # redis 默认端口是 6379
    port: 6379

3)配置 RedisTemplate

这里替换序列化器是因为 , RedisTemplate 默认的序列化方案是 JdkSerializationRedisSerializer,它将对象序列化为字节数组。

java 复制代码
@Configuration
public class RedisTemplateConfig {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 自定义的string序列化器
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // jackson 序列化器
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();

        // kv 序列化
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(jsonRedisSerializer);

        // hash 序列化
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);

        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }
}

使用例子

1)Redis 使用工具类

java 复制代码
public class RedisUtil {

    @SuppressWarnings("unchecked")
    private static RedisTemplate<Object, Object> redisTemplate = SpringUtil.getBean("redisTemplate", RedisTemplate.class);

    /**
     * 指定键的值增加
     * @param key 键
     * @param num  要增加的数
     * @return
     */
    public static int incrementInt(String key,int num){
        Long increment = redisTemplate.opsForValue().increment(key,num);
        return increment.intValue();
    }
    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     */
    public static void expire(String key, long time) {
        if (time > 0) {
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
    }

    public static long getExpire(String key){
        return redisTemplate.getExpire(key);
    }

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public static Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 获取数据
     *
     * @param key 键
     * @return 对应的键值
     */
    public static Map<Object, Object> getMap(String key) {
        return redisTemplate.opsForHash().entries(key);
    }


    /**
     * 缓存放入
     *
     * @param key   键
     * @param value 值
     */
    public static void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存放入
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     */
    public static void set(String key, Object value, long time) {
        if (time > 0) {
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        } else {
            set(key, value);
        }
    }

    /**
     * Map 缓存放入
     * @param key  键
     * @param map  对应多个键值
     */
    public static void putMap(String key, Map<Object, Object> map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    /**
     * Map 缓存放入
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     */
    public static void putMap(String key, Map<Object, Object> map, long time) {
        redisTemplate.opsForHash().putAll(key, map);
        if (time > 0) {
            expire(key, time);
        }
    }

    /**
     * list 缓存放入,尾部添加
     * @param key 键
     * @param value 值
     */
    public static void pushList(String key, Object value) {
        redisTemplate.opsForList().rightPush(key, value);
    }

    /**
     * list 缓存放入,尾部添加, 批量存放 list
     * @param key
     * @param list
     */
    public static void pushListAll(String key, List<Object> list) {
        if (list != null){
            redisTemplate.opsForList().rightPushAll(key, list);
        }
    }

    /**
     * 通过 key 获取 list
     */
    public static List<Object> getAllList(String key){
        return redisTemplate.opsForList().range(key, 0, -1);
    }

}

2)TestRdsController

如果没有使用 lomback,swagger,可以将对应的注解删除掉

java 复制代码
/**
 * 用于测试 rds
 * @author fei
 *
 */
@Slf4j
@RestController
@RequestMapping("/")
@Api(value = "测试 RDS API", tags = {"测试 RDS API"})
public class TestRdsController extends BaseController {

    @Autowired
    TestRdsService testRdsService;

    @GetMapping(value = "/rds/setString")
    @OperationLog(name="set String",type = OperationLogType.CREATE)
    @ApiOperation(value = "set String")
    public String rdsSetString(@ApiParam(value = "key", required = true) @RequestParam(value = "key")String key,
                                          @ApiParam(value = "value", required = true) @RequestParam(value = "value")String value) {
        testRdsService.rdsSetString(key, value);
        return "操作成功!");
    }

    @GetMapping(value = "/rds/getString")
    @ApiOperation(value = "get String")
    public String rdsGetString(@ApiParam(value = "key", required = true) @RequestParam(value = "key")String key) {
        String value = testRdsService.rdsGetString(key);
        return value;
    }

    @GetMapping(value = "/rds/putMap")
    @ApiOperation(value = "putMap")
    public String rdsPutMap(@ApiParam(value = "key", required = true) @RequestParam(value = "key") String key,
                    @ApiParam(value = "name", required = true) @RequestParam(value = "name") String name,
                    @ApiParam(value = "age", required = true) @RequestParam(value = "age") Integer age) {
        testRdsService.putMap(key, name, age);
        return "操作成功";
    }

    @GetMapping(value = "/rds/getMap")
    @ApiOperation(value = "getMap")
    public Map<Object, Object> getMap(@ApiParam(value = "key", required = true) @RequestParam(value = "key") String key) {
        Map<Object, Object> map = testRdsService.getMap(key);
        return map;
    }

    @GetMapping(value = "/rds/pushList")
    @ApiOperation(value = "list 缓存放入,尾部添加")
    public String pushList(@ApiParam(value = "key", required = true) @RequestParam(value = "key") String key,
                                                   @ApiParam(value = "value", required = true) @RequestParam(value = "value") Object value) {
        testRdsService.pushList(key, value);
        return "操作成功";
    }

    @GetMapping(value = "/rds/pushAllList")
    @ApiOperation(value = "将list数据全部放入 list 缓存")
    public String pushAllList(@ApiParam(value = "key", required = true) @RequestParam(value = "key") String key,
                                      @ApiParam(value = "list", required = true) @RequestParam(value = "list") List<Object> list) {
        testRdsService.pushListAll(key, list);
        return "操作成功";
    }

    @GetMapping(value = "/rds/getAllList")
    @ApiOperation(value = "通过 key 获取所有 list")
    public List<Object> getAllList(@ApiParam(value = "key", required = true) @RequestParam(value = "key") String key) {
        List<Object> allList = testRdsService.getAllList(key);
        return allList;
    }

}

3)TestRdsService

java 复制代码
/***
 * @author fei
 * @create 2024/11/20 9:12
 **/
public interface TestRdsService {

    void rdsSetString(String key, String value);

    String rdsGetString(String key);

    void putMap(String key, String name, Integer age);

    Map<Object, Object> getMap(String key);

    void pushList(String key, Object value);

    void pushListAll(String key, List<Object> list);

    List<Object> getAllList(String key);

}

4)TestRdsServiceImpl

java 复制代码
/***
 * @author fei
 * @create 2024/11/20 9:12
 **/
@Service
public class TestRdsServiceImpl implements TestRdsService {

    @Override
    public void rdsSetString(String key, String value) {
        RedisUtil.set(key, value);
    }

    @Override
    public String rdsGetString(String key) {
        Object o = RedisUtil.get(key);
        if (o == null){
            return "";
        }
        return (String)o;
    }

    @Override
    public void putMap(String key, String name, Integer age) {
        Map<Object, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("age", age);
        RedisUtil.putMap(key, map, 10000);
    }

    @Override
    public Map<Object, Object> getMap(String key) {
        return RedisUtil.getMap(key);
    }

    @Override
    public void pushList(String key, Object value) {
        RedisUtil.pushList(key, value);
    }

    @Override
    public void pushListAll(String key, List<Object> list) {
        RedisUtil.pushListAll(key, list);
    }

    @Override
    public List<Object> getAllList(String key) {
        return RedisUtil.getAllList(key);
    }

}

5)测试

最后可以使用 swagger 或者 Apifox 等工具调用接口测试,或者直接写个测试用例也可以

相关推荐
尘浮生9 分钟前
Java项目实战II基于Java+Spring Boot+MySQL的共享汽车管理系统(源码+数据库+文档)
java·数据库·spring boot·mysql·微信小程序·小程序·汽车
雪碧聊技术9 分钟前
RabbitMQ3:Java客户端快速入门
java·开发语言·rabbitmq·amqp·spring amqp·rabbittemplate
Sinsa_SI17 分钟前
2024年9月中国电子学会青少年软件编程(Python)等级考试试卷(六级)答案 + 解析
开发语言·python·等级考试·电子学会·考级
济南信息学奥赛刘老师18 分钟前
GESP考试大纲
开发语言·c++·算法·青少年编程
九圣残炎22 分钟前
【从零开始的LeetCode-算法】3297. 统计重新排列后包含另一个字符串的子字符串数目 I
java·算法·leetcode
前期后期30 分钟前
Android 工厂设计模式的使用:咖啡机,可以做拿铁,可以做美式等等。
android·java·设计模式
许静知32 分钟前
第十章 JavaScript的应用
开发语言·javascript·ecmascript
froginwe1139 分钟前
SQLite Having 子句
开发语言
好开心331 小时前
js高级06-ajax封装和跨域
开发语言·前端·javascript·ajax·okhttp·ecmascript·交互
儿时可乖了1 小时前
优化 Spring Boot 性能
spring boot·spring