Codis高可用客户端连接及使用封装

Codis 是 redis高可用集群的一种实现方式,是豌豆荚开源的。相对其他方式,更容易实现水平扩展、扩容、分片等操作。

项目连接codis,常用的方式是使用 Jedis.

一、配置文件

#codis
codis.zkAddr=192.168.1.10:2181,192.168.1.11:2181,192.168.1.12:2181
codis.zk.proxy.dir=/jodis/appName
codis.zk.timeout=30000
codis.minIdle=20
codis.maxIdle=200
codis.maxActive=2000
codis.maxWait=3000

maven 依赖

 
     3.1.0
     0.5.1
 


    
        redis.clients
        jedis
        ${jedis.version}
    

     
         io.codis.jodis
         jodis
         ${codis.jodis.version}
         
             
                 redis.clients
                 jedis
             
         
     

 

二、代理层zk负载均衡请求封装

import io.codis.jodis.JedisResourcePool;
import io.codis.jodis.RoundRobinJedisPool;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author CleverApe
 * @Classname CodisClientHA
 * @Description Codis客户端高可用封装
 * @Date 
 * @Version V1.0
 */
@Configuration
public class CodisClientHA {

    private Logger logger = LogManager.getLogger(CodisClientHA.class);

    @Value("${codis.zkAddr}")
    private String zkAddr;

    @Value("${codis.zk.proxy.dir}")
    private String zkProxyDir;

    @Value("${codis.zk.timeout}")
    private int zkSessionTimeout;

    @Value("${codis.minIdle}")
    private int min_idle;

    @Value("${codis.maxIdle}")
    private int max_idle;

    @Value("${codis.maxActive}")
    private int max_active;

    @Value("${codis.maxWait}")
    private long max_wait;

    @Bean
    public JedisResourcePool getPool() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMinIdle(min_idle);
        poolConfig.setMaxIdle(max_idle);
        poolConfig.setMaxTotal(max_active);
        poolConfig.setMaxWaitMillis(max_wait);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        poolConfig.setBlockWhenExhausted(true);

        JedisResourcePool pool = RoundRobinJedisPool.create().poolConfig(poolConfig).curatorClient(zkAddr, zkSessionTimeout).zkProxyDir(zkProxyDir).build();
        logger.info("------------------- Codis Connection Pool Init Succeed  -------------------");
        return pool;
    }

}

三、codis使用接口服务封装

@Component
public class CodisService {

    private static final Logger logger = LoggerFactory.getLogger(CodisService.class);

    @Autowired
    private JedisResourcePool jedisPool;

    /**
     * 获取缓存
     *
     * @param key
     * @return
     */
    public String get(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.get(key);
        } catch (Exception e) {
            logger.error("codis get exception, key ={}. Exception:", key, e);
            return null;
        }
    }

    /**
     * 设置缓存
     *
     * @param key
     * @param value
     * @param seconds
     */
    public void setex(String key, String value, int seconds) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.setex(key, seconds, value);
        } catch (Exception e) {
            logger.error("codis setex exception, key = {}, value = {}, ttl = {}s . Exception:", key, value, seconds, e);
        }
    }

    /**
     * 删除缓存
     *
     * @param key
     */
    public void delete(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.del(key);
        } catch (Exception e) {
            logger.error("codis delete exception, key = {}. Exception:", key, e);
        }
    }

    public boolean exists(String key) {
        boolean rs = false;
        try (Jedis jedis = jedisPool.getResource()) {
            rs = jedis.exists(key);
        } catch (Exception e) {
            logger.error("codis exists exception, key = {}. Exception:", key, e);
        }
        return rs;
    }

    public ScanResult> hscan(String key, int cursor, ScanParams params) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hscan(key, String.valueOf(cursor), params);
        } catch (Exception e) {
            logger.error("codis exists exception, key = {}. Exception:", key, e);
        }
        return null;
    }
}

 

你可能感兴趣的:(Java,Redis,Cache)