package com.cku.config; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.codec.JsonJacksonCodec; import org.redisson.config.Config; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import java.util.List; /** * NOTE:动态生成RedissonClient,适配sentinel集群模式和单机模式 */ public class RedissonClientBeanFactory implements FactoryBean, InitializingBean, DisposableBean { private RedissonClient redissonClient; private boolean sentinel; private String singleServerAddress; private String sentinelMasterName; private List sentinelServerAddressList; @Override public RedissonClient getObject() throws Exception { return redissonClient; } @Override public Class getObjectType() { return RedissonClient.class; } @Override public boolean isSingleton() { return true; } @Override public void afterPropertiesSet() throws Exception { Config config = new Config(); if (sentinel) { String[] arr = new String[sentinelServerAddressList.size()]; sentinelServerAddressList.toArray(arr); config.useSentinelServers().setMasterName(sentinelMasterName).addSentinelAddress(arr); } else { config.useSingleServer().setAddress(singleServerAddress).setConnectionMinimumIdleSize(10);; } //使用json序列化方式 config.setCodec(new JsonJacksonCodec()); redissonClient = Redisson.create(config); } public void setSentinel(boolean sentinel) { this.sentinel = sentinel; } public void setSingleServerAddress(String singleServerAddress) { this.singleServerAddress = singleServerAddress; } public void setSentinelMasterName(String sentinelMasterName) { this.sentinelMasterName = sentinelMasterName; } public void setSentinelServerAddressList(List sentinelServerAddressList) { this.sentinelServerAddressList = sentinelServerAddressList; } @Override public void destroy() throws Exception { redissonClient.shutdown(); redissonClient = null; } }