spring boot集成redis,以及配置database不生效问题

备注:记录一次spring-boot + redis 配置redis.database后,仍然使用db0默认库的情况。

springboot集成redis及相关问题

1. spring boot集成redis

redis集成依赖:

xml 复制代码
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!-- redis依赖commons-pool 这个依赖一定要添加 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>

redis配置

yaml 复制代码
spring:
  redis:
    host: xxxxx
    port: 6379
    password: xxxx
    database: 1
    jedis:
      pool:
        max-active: 10
        max-idle: 10
        min-idle: 0

序列化

java 复制代码
@Configuration
public class RedisConfig {
    /**
     * @Author: Huey
     * @Date: 2024/1/12 18:24
     * @Params:
     * @Return:
     * @Description: 初始化设置redis序列化类型,否则会出现乱码
     **/
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //使用fastjson序列化
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
        // value值的序列化采用fastJsonRedisSerializer
        template.setValueSerializer(fastJsonRedisSerializer);
        template.setHashValueSerializer(fastJsonRedisSerializer);
        // key的序列化采用StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);

        return template;
    }
}	

完成以上配置,即redis已经正常集成进入项目。

2. 集成redission redis分布式锁等快捷管理工具

集成依赖

xml 复制代码
  <!-- redis便捷分布式锁管理 -->
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version>${redisson.version}</version>
        </dependency>

配置注入

java 复制代码
@Configuration
public class RedissionConfig {
    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.database}")
    private int database;

    @Bean
    public RedissonClient getRedisson() {
        Config config = new Config();
        config.useSingleServer().
                setAddress("redis://" + redisHost + ":" + port)
                .setPassword(password)
        config.setCodec(new JsonJacksonCodec());
        return Redisson.create(config);
    }
}

示例

完成以上配置,即可正常使用了

java 复制代码
@Autowired
private RedissonClient redissonClient;

 RLock rLock = redissonClient.getLock(lockName);
 if (rLock.isLocked()) {
     //当前锁正在使用,当前用户还在同步订单,不处理业务
     logger.info("method handleReceiptMsg重复加锁,请求入参:{},不处理业务,当前锁状态:{}", JSONObject.toJSONString(payRqst), rLock.isLocked());
     return Result.error("handleReceiptMsg重复加锁");
 }
boolean isLocked = rLock.tryLock(RedisLockNameConstants.ORDER_SYNC_LOCK_TIME, TimeUnit.SECONDS);

3. 配置redis database不生效

如果是单独仅集成redis,database 配置是肯定生效的,因为没有影响,这里记录一个遇到的情景:

即:当spring-boot集成redis后,同时集成redission使用redis锁相关管理插件,此时,配置了RedissonClient,注入了Config配置,即第二部中的代码部分。而第一步中集成redis时,使用redistemplate仅仅只是对其做了序列化,至于redistemplate加载的配置,全靠程序默认加载,那么这里就涉及了一个加载顺序问题。

springboot 的 @Configuration 也会默认加载redis的配置,步骤二中构建RedissonClient时候,也构建了Config对象,这个里面会覆盖掉RedisConfig里的配置,所以,在构建RedissonClient时候,设置database即可生效。

java 复制代码
 @Bean
 public RedissonClient getRedisson() {
      Config config = new Config();
      config.useSingleServer().
              setAddress("redis://" + redisHost + ":" + port)
              .setPassword(password)
              //指定redis db库
              .setDatabase(database);
      config.setCodec(new JsonJacksonCodec());
      return Redisson.create(config);
  }
相关推荐
小七mod2 分钟前
【Spring】Java SPI机制及Spring Boot使用实例
java·spring boot·spring·spi·双亲委派
码农小站1 小时前
ClickHouse 时间范围查询:精准筛选「本月数据」
数据库
上上迁1 小时前
分布式接口幂等性的演进和最佳实践,含springBoot 实现(Java版本)
java·spring boot·分布式
paopaokaka_luck1 小时前
基于SpringBoot+Vue的非遗文化传承管理系统(websocket即时通讯、协同过滤算法、支付宝沙盒支付、可分享链接、功能量非常大)
java·数据库·vue.js·spring boot·后端·spring·小程序
小疯仔2 小时前
navicat导出数据库的表结构
数据库
TOSUN同星2 小时前
干货分享 | TSMaster DBC编辑器操作指南:功能详解+实战示例
数据库·oracle·编辑器·汽车·软件工程
huihui4503 小时前
一天一道Sql题(day01)
数据库
~尼卡~3 小时前
软考(软件设计师)数据库原理:事务管理,备份恢复,并发控制
数据库·软件设计师-软考
八九燕来3 小时前
Django双下划线查询
数据库·django·sqlite
眠りたいです3 小时前
Mysql常用内置函数,复合查询及内外连接
linux·数据库·c++·mysql