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

二、代理層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<Map.Entry<String, String>> 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;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章