springboot集成redisson

阅读更多

添加依赖:


            org.redisson
            redisson
            3.5.0
        

 

yml配置文件:

单机配置:redisson-single.yml

singleServerConfig:
  idleConnectionTimeout: 10000
  pingTimeout: 1000
  connectTimeout: 10000
  timeout: 3000
  retryAttempts: 3
  retryInterval: 1500
  reconnectionTimeout: 3000
  failedAttempts: 3
  password: 123456
  subscriptionsPerConnection: 5
  clientName: null
  address: "redis://192.168.200.64:6379"
  subscriptionConnectionMinimumIdleSize: 1
  subscriptionConnectionPoolSize: 50
  connectionMinimumIdleSize: 32
  connectionPoolSize: 64
  database: 0
  dnsMonitoring: false
  dnsMonitoringInterval: 5000
threads: 0
nettyThreads: 0
codec: ! {}
"transportMode":"NIO"

 

集群配置:redisson-cluster.yml

clusterServersConfig:
  idleConnectionTimeout: 10000
  pingTimeout: 1000
  connectTimeout: 10000
  timeout: 3000
  retryAttempts: 3
  retryInterval: 1500
  reconnectionTimeout: 3000
  failedAttempts: 3
  password: null
  subscriptionsPerConnection: 5
  clientName: null
  loadBalancer: ! {}
  slaveSubscriptionConnectionMinimumIdleSize: 1
  slaveSubscriptionConnectionPoolSize: 50
  slaveConnectionMinimumIdleSize: 32
  slaveConnectionPoolSize: 64
  masterConnectionMinimumIdleSize: 32
  masterConnectionPoolSize: 64
  readMode: "SLAVE"
  nodeAddresses:
    "redis://redis-server:6371"
    "redis://redis-server:6372"
    "redis://redis-server:6373"
  scanInterval: 1000
threads: 0
nettyThreads: 0
codec: ! {}
"transportMode":"NIO"

 

注入bean,自动加载配置文件:

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;

@Configuration
public class RedissonConfig {

    @Value("${redisCluster}")
    private boolean redisCluster;

    @Bean
    public RedissonClient redissonClient() throws IOException {
        return Redisson.create(
                Config.fromYAML(new ClassPathResource("redisson-" + (redisCluster ? "cluster" : "single") + ".yml").getInputStream())
        );
    }
}

 

 使用:

@Component
public class test{

    @Autowired
    private RedissonClient redissonClient;
    
    
    public void test(){
        RLock lock= redissonClient.getLock("test");
         try {
                lock.lock();
                ......业务代码略
         } catch (Exception ex) {
                log.error("同步数据到中心失败", ex);
            } finally {
                lock.unlock();
            }

    }
}

 

你可能感兴趣的:(springboot集成redisson)