Jedis+spring集成

jedis,redis的java客户端实现,对外调用的类只需要了解Jedis,JedisPool,JedisPoolConfig,JedisSharedInfo,ShardedJedisPool,ShardedJedis即可满足基本的使用,其中带shared的类是实现分片连接池的类(适用Redis集群)。
下面通过spring的容器来整合jedis,通过spring的整合能更简洁灵活的配置jedis。

Client: http://redis.io/clients
源码: https://github.com/xetorthio/jedis

实现过程:
1、maven引入jar
spring的jar
jedis的jar:

    redis.clients
    jedis
    2.0.0
 

2、spring-redis.xml
需要spring管理的两个类JedisPoolConfig和JedisPool
redis连接池的配置
redis连接池


 
    
    
    
    
	
  
	
      
          
          
          
          
      
    
    
    
		
		
		
		

    
    


redis.properties
# Redis settings
redis.host=127.0.0.1
redis.port=6379
redis.timeout=3000
#redis.pass=
 
redis.maxIdle=300
redis.maxActive=600
redis.maxWait=1000
redis.testOnBorrow=true

3、web.xml


	Archetype Created Web Application
 
	
	
		contextConfigLocation
		classpath:conf/spring-redis.xml
	
	
	
		org.springframework.web.context.ContextLoaderListener
		
	
 
	
	
		appServlet
		org.springframework.web.servlet.DispatcherServlet
		
			contextConfigLocation
			classpath:conf/spring-mvc.xml
		
		1
	
	
		appServlet
		/
	
 
	
	
		30
	
 


4、 JedisUtil
jedis公共类,封装对redis操作的方法
package com.akk.redis.util;
 
import javax.management.RuntimeErrorException;
 
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;
 
import com.alibaba.dubbo.common.utils.Assert;
 
@Component
public class JedisUtil{
 
	private static Logger logger= Logger.getLogger(JedisUtil.class);  
 
    @Autowired
    private JedisPool jedisPool;
 
	public static final int EXPIRE = 5 * 60;
	
	public static final String LOCKED = "TRUE";
	
	/**
	 * 从redis连接池取得实例
	 * @return
	 */
	public Jedis getJedis() {
		Jedis jedis;
		jedis = jedisPool.getResource();
		return jedis;
	}
	/**
	 * 释放redis回连接池
	 * @param jedis
	 */
	public void releaseJedis(Jedis jedis) {
		if (jedis != null) {
			jedisPool.returnResource(jedis);
		}
	}
	
	/**
	 * 获取key的value
	 * @param key
	 * @return
	 */
	public String getCacheValue(String key) {
        String string = new String();
            try {
                Assert.notNull(this, "jedisUtil 为空");
                Jedis jedis = this.getJedis();
                string = jedis.get(key);
                System.out.println("key:"+string);
                this.releaseJedis(jedis);
            } catch (Exception e) {
                logger.error("in get redis key="+ key, e);
            }

        return string;
    }
	
	/**
	 * 更新key的value
	 * @param key
	 * @param value
	 * @return
	 */
    public int updateCache(String key, String value) {
        try {
            Assert.notNull(this, "jedisUtil 为空");
            Jedis jedis = this.getJedis();
            String result = jedis.set(key, value) ;
            this.releaseJedis(jedis);
        } catch (Exception e) {
            logger.error("in update redis key="+ key, e);
        }
        return 1;
    }
    
    /**
     * 删除key的value
     * @param key
     * @return
     */
    public int removeCache(String key) {
        try {
            Assert.notNull(this, "jedisUtil 为空");
            Jedis jedis = this.getJedis();
            long result = jedis.del(key) ;
            this.releaseJedis(jedis);
        } catch (Exception e) {
            logger.error("in del redis key="+ key, e);
        }
        return 1;
    }													
    
    /**
     * 带事务+watch 的更新方法
     * @param key
     * @param value
     */
    public void updateWatchKey(String key,String value) {
        try {
	    	Jedis jedis = this.getJedis();
	    	//watch key
	    	jedis.watch(key);
	    	//取得key的value
	    	value = jedis.get(key);
	    	if (value == null || value.equals("UNLOCK")) {
	    		//开启事务
		    	Transaction tx = jedis.multi();
		    	//设置key,value;EXPIRE为key的过期时间
		    	tx.setex(key, EXPIRE, LOCKED);
		    	//提交事务,并判断
		    	if(null == tx.exec()){
		    		this.releaseJedis(jedis);
		    		throw new RuntimeException("key:"+key+"更新失败");
		    	}
	    	}else{
	    		this.releaseJedis(jedis);
	    		throw new RuntimeException("key:"+key+"更新失败");
	    	}
	    	this.releaseJedis(jedis);
        } catch (Error e) {
            throw new RuntimeErrorException(e);
        }
	}
}

5、 RedisController
最后是springmvc的controller
package com.akk.controller;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
import com.akk.redis.util.JedisUtil;
 
@Controller
public class RedisController {
	
	@Autowired
	private JedisUtil jedisUtil;
 
	/**
	 * 
	 * @param str
	 * @return
	 * @throws InterruptedException
	 */
	@RequestMapping(value="/redis", method={RequestMethod.POST,RequestMethod.GET})
	public String redis(String str) throws InterruptedException{
 
		//用户id
		String userId="11";
		//奖品类型
		String rewardType="77";
		//用户+奖品
		String key = userId+rewardType;
		
		try {
			String getReward = jedisUtil.getCacheValue(key);
	    	if(null == getReward || getReward.equals("")){
	    		System.out.println("start-on");
	    		jedisUtil.updateWatchKey(key, "on");
				System.out.println("on");
	    	}else{
	    		System.out.println("not null");
	    	}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return "index";
	}
}
•


总结

你可能感兴趣的:(Java,redis,spring)