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);
  }
相关推荐
一休哥助手6 分钟前
Redis 五种数据类型及底层数据结构详解
数据结构·数据库·redis
翔云12345614 分钟前
MVCC(多版本并发控制)
数据库·mysql
代码敲上天.30 分钟前
数据库语句优化
android·数据库·adb
盒马盒马1 小时前
Redis:zset类型
数据库·redis
2401_854391081 小时前
Spring Boot大学生就业招聘系统的开发与部署
java·spring boot·后端
静听山水1 小时前
mysql语句执行过程
数据库·mysql
虽千万人 吾往矣1 小时前
golang gorm
开发语言·数据库·后端·tcp/ip·golang
杨荧1 小时前
【JAVA开源】基于Vue和SpringBoot的洗衣店订单管理系统
java·开发语言·vue.js·spring boot·spring cloud·开源
2401_857610032 小时前
SpringBoot实现:校园资料分享平台开发指南
服务器·spring boot·php
mariokkm2 小时前
Django一分钟:在Django中怎么存储树形结构的数据,DRF校验递归嵌套模型的替代方案
数据库·django·sqlite