Java complete tutorial on using Redis with Jedis

Using Java to operate Redis requires jedis-2.1.0.jar, download address: http://files.cnblogs.com/liuling/jedis-2.1.0.jar.zip

If you need to use Redis connection pool, you also need commons-pool-1.5.4.jar, download address: http://files.cnblogs.com/liuling/commons-pool-1.5.4.jar.zip

 

In general, using Jedis requires the use of a connection pool to obtain connections

First, the configuration and use of the connection pool

First configure some configuration information of the jedis connection pool in spring

  

<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="${redis.maxTotal}"></property>
		<property name="maxIdle" value="${redis.maxIdle}"></property>
		<property name="minIdle" value="${redis.minIdle}"></property>
		<property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property>
		<property name="testOnBorrow" value="${redis.testOnBorrow}"></property>
		<property name="testOnReturn" value="${redis.testOnReturn}"></property>
		<property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"></property>
		<property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"></property>
		<property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"></property>
	</bean>

 The specific description information of these configurations can be briefly mentioned:

 

 

maxTotal: maximum number of connections

maxIdle: the maximum number of idle connections

minIdle: Minimum number of idle connections

maxWaitMillis: The maximum number of milliseconds to wait when getting a connection,

testOnBorrow: Check validity when getting connection

testOnRetrun: Whether to perform the validate operation in advance when returning to the pool

minEvictableIdleTimeMillis: The minimum time for an object to stay in the idle state at least before it can be scanned and expelled by Idle, object evitor

numTestsPerEvictionRun: idle, object, the number of objects scanned by evitor each time

timeBetweenEvictionRunsMillis: scan interval for releasing connections

After configuring the jedis connection pool configuration, you can configure the connection pool

 

 

 

<bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy">
		<constructor-arg index="0" ref="jedisPoolConfig" />
		<constructor-arg index="1" value="${redis.hostName}" type="java.lang.String"/>
		<constructor-arg index="2" value="${redis.port}" type="int" />
		<constructor-arg index="3" value="${redis.timeout}"	type="int" />
		<constructor-arg index="4" value="${redis.auth}" type="java.lang.String"/>
	</bean>

 The connection pool configuration, name address and port password of jedis are configured here.

 

 

. Even if the connection pool is configured, then we can configure the class for obtaining the connection:

 

import redis.clients.jedis.Jedis;
import redis.clients.util.Pool;


public class Test {

	private Pool<Jedis> redisPool;

	public Pool<Jedis> getRedisPool() {
		return redisPool;
	}

	public void setRedisPool(Pool<Jedis>  redisPool) {
		this.redisPool = redisPool;
	}

	public Jedis getJedis() {
		try {
			Jedis jedis = redisPool.getResource();
			if (jedis == null) {
				return null;
			}
			return jedis;
		} catch (Exception e) {
		}
		return null;
	}

	public void release(Jedis jedis) {
		if (jedis != null) {
			jedis.close();
		}
	}
	public void init(){
		
	}

	public static void main(String[] args) {
	}
}

 In this way, we can write a tool class to manage the acquisition and closure of jedis, etc.:

 

 public static Jedis getJedis(Integer index){

        Jedis jedis = null;

        JedisClient jedisClient = (JedisClient)ctx.getBean("jedisClient");

        if(null!=jedisClient){

            jedis = jedisClient.getJedis();

        }

        try{

            jedis.select(index);

        }catch(Exception e){

            jedis.select(JedisDBEnum.DEFAULT.getIndex().intValue());

            log.info("getJedis index:"+index+" and default select db 0",e);

        }

        return jedis;

 

    }

 

这一段很简单就是获取一个jedis连接,然后选择几号库,当然,用完jedis之后需要关闭连接

public static void closeJeids(Jedis jedis){

        try{

            if(null!=jedis){

                jedis.close();

            }

        }catch(Exception e){

                    

        }

 

    }

这就是通过jedis连接池获取jedis连接的全部流程了

 

 

 获取到jedis之后就可以往jedis里面放数据或取数据了,在redis中放对象可以将对象序列化或者是转换成map放入,下面先列出第二种方式的例子

public class SeriaUtil {
	
	/**
	 * 将对象转为map,Integer, BigDecimal Double ,Long默认值为空
	 * @param clazz
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String , String> getMapfromObject(Class<?> clazz , Object obj){
		Map<String , String > map = new HashMap<String , String>();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerDefaultValueProcessor(Integer.class, new DefaultValueProcessor() {
			@Override
			public Object getDefaultValue(Class arg0) {
				return null;
			}
		});
		jsonConfig.registerDefaultValueProcessor(BigDecimal.class, new DefaultValueProcessor() {
			@Override
			public Object getDefaultValue(Class arg0) {
				return null;
			}
		});
		jsonConfig.registerDefaultValueProcessor(Long.class, new DefaultValueProcessor() {
			@Override
			public Object getDefaultValue(Class arg0) {
				return null;
			}
		});
		jsonConfig.registerDefaultValueProcessor(Double.class, new DefaultValueProcessor() {
			@Override
			public Object getDefaultValue(Class arg0) {
				return null;
			}
		});
		JSONObject jsonObj = JSONObject.fromObject(obj , jsonConfig);
		Iterator it = jsonObj.keys();
		while(it.hasNext()){
			String key = String.valueOf(it.next()) ;
			Object data = jsonObj.get(key);
			if(null != data &&!(data instanceof JSONNull)){
				map.put(key, data.toString());
			}else{
				map.put(key, "");
			}
		}
		return map ;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getObjet(Jedis jedis , String key , Class<T> clazz){
		Map<String , String> map =jedis.hgetAll(key);
		if(map == null || map.isEmpty() ){
			return null ;
		}
		Map<String , String > nMap = new HashMap<String , String>();
		for(String keys: map.keySet()){
			if(map.get(keys)!=null && !map.get(keys).equals("")){
				nMap.put(keys, map.get(keys));
			}
		}
		T t = null ;
		try {
			if(nMap == null || nMap.isEmpty()){
				return null ; 
			}
			Constructor<?> c = clazz.getConstructor(Map.class);
            t =  (T) c.newInstance(map);
			
		} catch (Exception e) {
			 JSONObject json = JSONObject.fromObject(map);
	         t =  (T) JSONObject.toBean(json,clazz);
		}
		return t ;
	}
}

 

 

public class JedisTest {
	public static void main(String[] args) {
		ApplicationContext ap = new ClassPathXmlApplicationContext("main/java/conf/applicationContext.xml");
		JedisClient jedisClient = (JedisClient)ap.getBean("jedisClient");
		Jedis jedis = jedisClient.getJedis();
		jedis.select(0);
		jedis.sadd("name:123", "dengwei");
		jedis.del("name:123");
		SeriaBean bean = new SeriaBean ();
		bean.setAge(23);
		bean.setName("dengwe");
		jedis.hmset("bean", SeriaUtil.getMapfromObject(SeriaBean.class, bean));
		SeriaBean bb = SeriaUtil.getObjet(jedis, "bean", SeriaBean.class);
		System.out.println(bb);
		jedis.close();
	}
}

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327031350&siteId=291194637