您的位置:首页 > 数据库 > Redis

redis客户端jedis基于spring搭建单节点或者集群线程池连接

2017-09-28 14:05 831 查看
基于jedis线程池搭建单节点或集群连接完整代码

 <dependency>
     <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
   <version>2.9.0</version>
</dependency>

1:properties配置文件

###########

redis.model=single

redis.url=10.128.90.60:6377

redis.testOnBorrow=true

redis.testOnReturn=true

redis.maxTotal=400

redis.maxIdle=5

redis.jmxEnable=true

redis.timeout=3000

redis.masterName=mymaster

redis.password=ustc

###########

2:jedis信息类

-----------------------------------------------------------

package com.gccloud.www.OCTP.support.jedis;

public class JedisConfig {

public static final String SINGLE_MODEL = "single";
public static final String SENTINEL_MODEL = "sentinel";

private String model;
private String url;
private boolean testOnBorrow;
private boolean testOnReturn;
private int maxTotal;
private int maxIdle;
private boolean jmxEnable;
private int timeout;
private String masterName;
private String password;

     public static String getSingleModel() {
return SINGLE_MODEL;
}
public static String getSentinelModel() {
return SENTINEL_MODEL;
}

       //省略get、set方法

-----------------------------------------------------------

3:  jedisConfig的bean配置

*************************************

<bean id="jedisConfig" class="com.gccloud.www.OCTP.support.jedis.JedisConfig">
<!-- redis连接类型,single单节点,sentinel哨兵 模式 -->
<property name="model" value="${redis.model}" />
<!-- redis连接信息,ip:port -->
<property name="url" value="${redis.url}" />
<!-- 检测开关 -->
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
<!-- 检测开关 -->
<property name="testOnReturn" value="${redis.testOnReturn}" />
<!-- 最大连接数 -->
<property name="maxTotal" value="${redis.maxTotal}" />
<!-- 最大空闲 -->
<property name="maxIdle" value="${redis.maxIdle}" />
<!-- 最大连接数 -->
<property name="jmxEnable" value="${redis.jmxEnable}" />
<!-- 读取超时时间 -->
<property name="timeout" value="${redis.timeout}" />
<!-- masterName,哨兵模式需要配置 -->
<property name="masterName" value="${redis.masterName}" />
<!-- 密码 -->
<property name="password" value="${redis.password}" />
</bean>

*************************************

4:工厂类 JedisPoolFactory

*************************************

package com.gccloud.www.OCTP.support.jedis;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;

import com.gccloud.www.OCTP.support.jedis.client.JedisSentinelFacotry;

import com.gccloud.www.OCTP.support.jedis.client.JedisSingleFactory;

public abstract class JedisPoolFactory {

private JedisConfig jedisConf;
private static final Logger LOGGER = LoggerFactory.getLogger(JedisPoolFactory.class);
/**
* 工厂方法
* @param jedisConf
* @return
*/
public static JedisPoolFactory getRedisFactory(JedisConfig jedisConf){

LOGGER.info("准备加载jedis对象,{}",jedisConf);

if(JedisConfig.SINGLE_MODEL.equals(jedisConf.getModel())){

LOGGER.info("加载单节点jedis对象!");

return new JedisSingleFactory(jedisConf);

}else if (JedisConfig.SENTINEL_MODEL.equals(jedisConf.getModel())){

LOGGER.info("加载哨兵模式jedis对象!");

return new JedisSentinelFacotry(jedisConf);

}else{
LOGGER.info("jedis模式未知,无法加载!");
throw new RuntimeException("jedis模式未知,无法加载!" + jedisConf);
}

}

/**
* 获取jedis连接实例
* @return
*/
public abstract Jedis getJedis();

/**
* 归还实例
* @param jedis
*/
public abstract void closeJedis(Jedis jedis);

}

*************************************

5-1:Sentinel模式

*************************************

import java.util.HashSet;

import java.util.Set;

import org.apache.commons.collections.CollectionUtils;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisSentinelPool;

import com.gccloud.www.OCTP.support.jedis.JedisPoolFactory;

import com.gccloud.www.OCTP.support.jedis.JedisConfig;

/**

 * Sentinel模式的jedis连接

 * @author feng

 *

 */

public class JedisSentinelFacotry extends JedisPoolFactory{

private JedisConfig jedisConf;
private JedisSentinelPool jSentinelPool;
private final static Logger LOGGER = LoggerFactory.getLogger(JedisSentinelFacotry.class);

public JedisSentinelFacotry(JedisConfig jedisConf){
this.jedisConf  = jedisConf;
initPool();
}

/**
* 初始化连接池
*/
private void initPool(){

LOGGER.info("初始化 redis Sentinel连接池! redisSentinelUrl={}",jedisConf.getUrl());

String[] urls = jedisConf.getUrl().split(",");
Set<String> urlset = new HashSet<String>();
CollectionUtils.addAll(urlset, urls);
GenericObjectPoolConfig gPoolConfig=new GenericObjectPoolConfig();
if(jedisConf.getMaxTotal() !=0 ){
gPoolConfig.setMaxTotal(jedisConf.getMaxTotal());
}
if(jedisConf.getMaxIdle() !=0){
gPoolConfig.setMaxIdle(jedisConf.getMaxIdle());
}
gPoolConfig.setJmxEnabled(jedisConf.isJmxEnable());
gPoolConfig.setTestOnBorrow(jedisConf.isTestOnBorrow());
gPoolConfig.setTestOnReturn(jedisConf.isTestOnReturn());

if(jedisConf.getPassword() != null && jedisConf.getPassword().trim().length() > 0){
jSentinelPool = new JedisSentinelPool(jedisConf.getMasterName(), urlset, gPoolConfig, jedisConf.getTimeout(), jedisConf.getPassword());
}else{
jSentinelPool = new JedisSentinelPool(jedisConf.getMasterName(), urlset, gPoolConfig, jedisConf.getTimeout());
}

LOGGER.info("jedis Sentinel连接池初始化完成!");
}

/**
* 获取jedis连接
* @return
*/
public synchronized Jedis getJedis(){

Jedis jedis  = null;
int count =0;
do{  

            try{   

                jedis = jSentinelPool.getResource();  

            } catch (Exception e) {  

            LOGGER.error("get redis failed!", e);

            e.printStackTrace();

                 // 销毁对象    

            jSentinelPool.returnBrokenResource(jedis);    

            }  

            count++;  

        }while(jedis==null && count<3 );  

        return jedis;

}

/**
* 归还连接
* @param jedis
* @param redisUrl
*/
public synchronized void closeJedis(Jedis jedis) { 

        if(jedis != null) {  

            try {

            jSentinelPool.returnResource(jedis);
} catch (Exception e) {
LOGGER.error("return redis failed!", e);
jSentinelPool.returnBrokenResource(jedis);
}  

        }  

    }

}

************************************

5-2:single模式

***********************************

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

import redis.clients.jedis.JedisPoolConfig;

import redis.clients.jedis.Protocol;

import com.gccloud.www.OCTP.support.jedis.JedisPoolFactory;

import com.gccloud.www.OCTP.support.jedis.JedisConfig;

public class JedisSingleFactory extends JedisPoolFactory{

private JedisConfig jedisConf;
private JedisPool jedisPool;

private static final Logger LOGGER = LoggerFactory.getLogger(JedisSingleFactory.class);

public JedisSingleFactory(JedisConfig jedisConf){
this.jedisConf = jedisConf;
initPool();

}

private void initPool() {
// TODO Auto-generated method stub

LOGGER.info("初始化 redis single连接池! single={}",jedisConf);

String jedisUrl = jedisConf.getUrl();
String[] ipAndPort = jedisUrl.split(":");
if(ipAndPort == null || ipAndPort.length !=2){
LOGGER.error("jedis single初始化失败,ip端口配置异常!");
throw new RuntimeException("jedis single初始化失败,ip端口配置异常!");
}
JedisPoolConfig gPoolConfig=new JedisPoolConfig();
if(jedisConf.getMaxIdle() != 0){

gPoolConfig.setMaxIdle(jedisConf.getMaxIdle());
}
if(jedisConf.getMaxTotal()!=0){

gPoolConfig.setMaxTotal(jedisConf.getMaxTotal());
}
gPoolConfig.setJmxEnabled(jedisConf.isJmxEnable());
gPoolConfig.setTestOnBorrow(jedisConf.isTestOnBorrow());
gPoolConfig.setTestOnReturn(jedisConf.isTestOnReturn());

if(jedisConf.getPassword() != null && jedisConf.getPassword().trim().length() > 0){
jedisPool = new JedisPool(gPoolConfig, ipAndPort[0], Integer.valueOf(ipAndPort[1]), jedisConf.getTimeout(), jedisConf.getPassword(), Protocol.DEFAULT_DATABASE);
}else{
jedisPool =  new JedisPool(gPoolConfig, ipAndPort[0], Integer.valueOf(ipAndPort[1]), jedisConf.getTimeout());
}

LOGGER.info("jedis single连接池初始化完成!");
}

/**
* 获取jedis连接
* @return
*/
public synchronized Jedis getJedis(){
Jedis jedis  = null;
int count =0;
do{  

            try{   

            LOGGER.debug("redis当前线程池活动数量:{},空闲数量{},等待数量{}",jedisPool.getNumActive(),jedisPool.getNumIdle());

           

                jedis = jedisPool.getResource();  

            } catch (Exception e) {  

            LOGGER.error("get redis failed!", e);

            e.printStackTrace();

                 // 销毁对象    

            jedisPool.returnBrokenResource(jedis);    

            }  

            count++;  

        }while(jedis==null && count<3 );  

        return jedis;
}

/**
* 归还连接
* @param jedis
* @param redisUrl
*/
public synchronized void closeJedis(Jedis jedis) { 

        if(jedis != null) {  

            try {

            jedisPool.returnResource(jedis);
} catch (Exception e) {
LOGGER.error("return redis failed!", e);
jedisPool.returnBrokenResource(jedis);
}  

        }  

    }

}

***********************************

6:main测试

***********************************

public static void main(String[] args) {

AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

        JedisConfig jedisConf =  (JedisConfig)applicationContext.getBean("jedisConfig");

        JedisPoolFactory jedisPoolFactory = JedisPoolFactory.getRedisFactory(jedisConf);

        Jedis jedis=jedisPoolFactory.getJedis();

        jedis.set("username", "zzh");

        System.out.println(jedis.get("username"));

       System.out.println(jedis.dbSize());

       jedis.close(); 

}

*********************************

附加:jedis 事务操作 

   Transaction tran = jedis.multi(); 

   tran.del();

   tran.rpush();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐