配置

org.redisson.Config

public class Config {
    static final Logger log = LoggerFactory.getLogger(Config.class);
	/**
	 * 通用配置
	 * Codec, threads, eventLoopGroup
	 */
    private Codec codec; // Redis 数据解编码器。用于读写 Redis 数据。
    private int threads = 16; // 所有 redis 节点客户端所共享的线程数量 默认值: current_processors_amount * 2
    private EventLoopGroup eventLoopGroup;
    /**
	 * 集群配置
	 * ClusterServersConfig 
	 */
    private ClusterServersConfig clusterServersConfig;


    private SentinelServersConfig sentinelServersConfig;
    private MasterSlaveServersConfig masterSlaveServersConfig;
    private SingleServerConfig singleServerConfig;
    private ReplicatedServersConfig replicatedServersConfig;
    private ConnectionManager connectionManager;

    private int nettyThreads = 32;
    private ExecutorService executor;
    private boolean referenceEnabled = true;
    private TransportMode transportMode;
    private long lockWatchdogTimeout;
    private long reliableTopicWatchdogTimeout;
    private boolean keepPubSubOrder;
    private boolean useScriptCache;
    private int minCleanUpDelay;
    private int maxCleanUpDelay;
    private int cleanUpKeysAmount;
    private NettyHook nettyHook;
    private ConnectionListener connectionListener;
    private boolean useThreadClassLoader;
    private AddressResolverGroupFactory addressResolverGroupFactory;
	// 一堆方法
}

Config 通用配置

Codec

默认值: org.redisson.codec.JsonJacksonCodec

Redis 数据解编码器。用于读写 Redis 数据。支持多种实现:
在这里插入图片描述

threads

默认值: current_processors_amount * 2

所有 redis 节点客户端所共享的线程数量。

eventLoopGroup

使用外部的 EventLoopGroup。
EventLoopGroup 通过自己的线程来处理所有和 Redis 服务器相连的 Netty 链接。
每个 Redisson 客户端会默认创建一个自己的 EventLoopGroup。
因此若相同的 JVM 中存在多个 Redisson 实例,它会在它们之间共享一个 EventLoopGroup。

只允许使用 io.netty.channel.epoll.EpollEventLoopGroup 或 io.netty.channel.nio.NioEventLoopGroup。

useLinuxNativeEpoll

默认值: false

当服务器绑定到 loopback 接口时激活一个 unix socket。
同样也用于激活 epoll 协议。
netty-transport-native-epoll 类库需包含在 classpath 中。

ClusterServersConfig 集群模式

集群配置官方文档

Elasticache 模式

Elasticache配置文档

单实例模式

单实例配置文档

Sentinel 模式

Sentinel配置文档

主从模式

主从模式配置

实例:

@Configuration
public class RedissonConfig {

    @Value("${redisson.host}")
    private String host;
    @Value("${redisson.port}")
    private String port;
    @Value("${redisson.database}")
    private int dataBase;
    @Value("${redisson.password}")
    private String password;

    @Bean
    public RedissonClient redissonClient(){
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://"+host+":"+port)
                .setPassword(password)
                .setDatabase(dataBase).setTimeout(30000);
        //使用json序列化方式
        Codec codec = new JsonJacksonCodec();
        config.setCodec(codec);
        return Redisson.create(config);
    }
}

application-dev.yml

redisson.host=# ip
redisson.port=# 端口 6379
redisson.password= #密码
redisson.database=# 针对 Redis 连接的数据库索引

使用

@RestController
public class Controller {
    @Resource
    private RedissonClient redissonClient;
    public void function(){
    	//1. string
    	RBucket<String> s1= redissonClient.getBucket("空间:key");// 建议
        s1.set("17855554444");
        String s = s1.get();

        //2. hash
        RMap<String, String> school = redissonClient.getMap("mapkey");
        school.put("s1","aa");
        school.get("s1");

        //3. list
        RBucket<List<User>> userList = redissonClient.getBucket("key");

        //4. 自增计数器
        RAtomicLong atomicLong = redissonClient.getAtomicLong("key");
        long l = atomicLong.incrementAndGet();
    
    }
    // 基于redisson 的互斥锁的分布式锁实现
    public void function2(){
    	//5. 基于redisson 的互斥锁的分布式锁实现
        ExecutorService executorService = Executors.newCachedThreadPool();

        // 互斥锁测试
        for (int i = 0; i < 5; i++) {
            executorService.submit(new MultipleThreadsRunTest());
            try {
                Thread.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            Thread.sleep(20000);
            System.out.println("主程序结束...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
        class MultipleThreadsRunTest implements Runnable {

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+ " 线程开始... ");
            RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
            try {
                boolean b1 = readWriteLock.writeLock().tryLock(1, 5, TimeUnit.SECONDS);
                if (b1){
                    System.out.println(Thread.currentThread().getName()+ " 读取锁成功... ");
                    Thread.sleep(4000);
                }else {
                    System.out.println(Thread.currentThread().getName()+ " 读取锁失败... ");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                System.out.println(Thread.currentThread().getName() + " 线程结束,准备释放锁... ");
                readWriteLock.writeLock().unlock();
            }

        }
    }

}

引用:
Redisson 官方文档中文翻译:https://www.bookstack.cn/read/redisson-doc-cn/config.md#cluster-mode
聊一聊Redis官方置顶推荐的Java客户端Redisson:https://zhuanlan.zhihu.com/p/264846738

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐