Bootstrap

SpringBoot集成Redisson

1.在pom.xml中导入

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.16.0</version>
</dependency>

2.在application.yaml中添加redisson配置也可以复用redis配置(此处复用redis配置)

spring:
  redis:
    database: 4
    host: 127.0.0.1
    port: 6379

针对不知道配置什么属性,可以查看RedissonAutoConfiguration源文件,从源文件中可以看到,RedissionProperties和RedisProperties文件都引进来了,说明两个文件里的配置信息都可以引用。

RedissonProperties中以spring.redis.redisson开头

RedisProperties中以spring.redis开头

RedissonAutoConfiguration创建RedissonClient流程

3.业务代码使用redisson

	@Resource
    RedissonClient redissonClient;
RLock lock = redissonClient.getLock(String.format(RedisKeys.LockKeys.ORDER_LOCK_KEY, orderId));
        boolean flag = Boolean.FALSE;
        try {
            if (!lock.tryLock(CommonConstant.LOCK_DEFAULT_WAIT_TIME_LENGTH,
                    CommonConstant.LOCK_DEFAULT_LEASE_TIME_LENGTH, TimeUnit.SECONDS)) {
                throw new BusinessException("获取锁失败");
            }
            // 业务逻辑代码
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }

另一种方案,通过指定destroyMethod,当应用关闭时,redissonClient也会关闭

@ConfigurationProperties(prefix = "redisson")
@Configuration
public class MyRedissonConfig {
    @Setter
    private String address;
    @Setter
    private Integer database;

    /**
     * 默认最小空闲连接数
     */
    @Setter
    private Integer minIdle;

    /**
     * 所有对Redisson的使用都是通过RedissonClient
     * @return
     * @throws IOException
     */
    @Bean(destroyMethod="shutdown")
    public RedissonClient redisson() throws IOException {
        //1、创建配置
        Config config = new Config();
        config.useSingleServer().setAddress(address).setDatabase(database).setConnectionMinimumIdleSize(minIdle);

        //2、根据Config创建出RedissonClient实例
        //Redis url should start with redis:// or rediss://
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }

}

;