SpringBoot 2.1.9 整合 Redisson分布式锁

官方参考文档

redisson-spring-boot-starter 官方文档

通过YAML文件配置单节点模式

一)、引入Redisson整合Spring Boot依赖

<!-- Spring Boot 相关依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!-- 引入Jedis客户端依赖 -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.1</version>
</dependency>
<!-- 引入Redisson依赖 -->
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.12.5</version>
</dependency>

 

二)、通过YAML文件配置Redisson单节点模式

需要另行创建redisson-single.yml文件,名字可以自定义,但是要和接下来的Bean配置一致

singleServerConfig:
  idleConnectionTimeout: 10000
  connectTimeout: 10000
  timeout: 3000
  retryAttempts: 3
  retryInterval: 1500
  # 如果Redis服务端配置有密码需要替换password的值
  password: null
  subscriptionsPerConnection: 5
  clientName: null
  # 替换为自己真实Redis服务端连接
  address: "redis://127.0.0.1:6379"
  subscriptionConnectionMinimumIdleSize: 1
  subscriptionConnectionPoolSize: 50
  connectionMinimumIdleSize: 24
  connectionPoolSize: 64
  database: 0
  dnsMonitoringInterval: 5000
threads: 16
nettyThreads: 32
codec: !<org.redisson.codec.FstCodec> {}
transportMode: "NIO"

 

三)、编写Redisson配置对象

/**
 * Redisson配置类
 *
 * @author MoCha
 * @date 2020/4/25
 */
@Configuration
public class RedissonConfig {
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redisson() throws IOException {
        return Redisson.create(
                Config.fromYAML(new ClassPathResource("redisson-single.yml").getInputStream()));
    }
}

 

四)、分布式锁运用

/**
 * 测试Redisson分布式锁
 *
 * @author MoCha
 * @date 2020/4/25
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RedissonController {
    private final RedissonClient redissonClient;

    @GetMapping("/test")
    public String testLock() {
        RLock coffeeLock = redissonClient.getLock("coffee");
        log.info("进入方法");
        try {
            // 尝试加锁,最多等待20秒,上锁以后5秒自动解锁
            Future<Boolean> coffeeLockFuture = coffeeLock.tryLockAsync(20, 5, TimeUnit.SECONDS);
            boolean result = coffeeLockFuture.get();
            if (result) {
                log.info("我获得了锁");
                Coffee coffee = coffeeService.getById(1);
                if (coffee.getStock() > 0) {
                    coffee.setStock(coffee.getStock() - 1);
                    coffeeService.updateById(coffee);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            log.info("我释放了锁");
            coffeeLock.unlock();
        }
        return "success";
    }
}

 

关于Redisson 中文Wiki文档的坑

明明都是官方Github的文档,但是中文语言的Wiki文档,在单节点模式配置很明显就问题,

刚开始我是看了中文的Wiki,然后发现报错,一看源码才发现SingleServerConfig和

org.redisson.config.Config根本就没有中文Wiki文档Yaml文件的一些配置。

然后我又看了英文文档的,发现两个文档的配置有出入。果断英文文档的配置是可以使用

的。配置后确实没问题。不得不说,这个坑,会把一开始看中文文档的朋友给整懵了。

Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "pingTimeout" (class org.redisson.config.SingleServerConfig), not marked as ignorable (25 known properties: "timeout", "subscriptionsPerConnection", "keepAlive", "sslKeystorePassword", "retryInterval", "retryAttempts", "idleConnectionTimeout", "sslTruststorePassword", "sslEnableEndpointIdentification", "address", "sslTruststore", "username", "connectTimeout", "subscriptionConnectionPoolSize", "password", "sslProvider", "tcpNoDelay", "connectionMinimumIdleSize", "subscriptionConnectionMinimumIdleSize", "sslKeystore", "pingConnectionInterval", "clientName", "connectionPoolSize", "database", "dnsMonitoringInterval"])
 at [Source: (StringReader); line: 3, column: 20] (through reference chain: org.redisson.config.Config["singleServerConfig"]->org.redisson.config.SingleServerConfig["pingTimeout"])
  • 1
  • 2

posted @ 2020-10-10 09:19  沙耶  阅读(1932)  评论(0编辑  收藏  举报