Jedis+spring集成

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


实现过程:
1、maven引入jar
spring的jar
jedis的jar:
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.0.0</version>
</dependency> 

2、spring-redis.xml
需要spring管理的两个类JedisPoolConfig和JedisPool
redis连接池的配置
redis连接池
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
    <context:annotation-config />
    <context:component-scan base-package="com.akk" />
    
    <!-- 加载redis配置文件 -->
	<context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/>
  
	<!-- redis连接池的配置 -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
        <property name="maxIdle" value="${redis.maxIdle}" />  
        <property name="maxActive" value="${redis.maxActive}" />  
        <property name="maxWait" value="${redis.maxWait}" />  
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
    </bean>  
    
    <!-- redis的连接池pool -->
    <bean id = "jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy">
		<constructor-arg index="0" ref="jedisPoolConfig" />
		<constructor-arg index="1" value="${redis.host}"/>
		<constructor-arg index="2" value="${redis.port}" type="int"/>
		<constructor-arg index="3" value="${redis.timeout}" type="int"/>
<!-- 		<constructor-arg index="4" value="${redis.pass}"/> -->
    </bean>
    
</beans>

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
<?xml version="1.0" encoding="UTF-8" ?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>Archetype Created Web Application</display-name>
 
	<!-- 读取spring配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:conf/spring-redis.xml</param-value>
	</context-param>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
 
	<!-- springMVC核心配置 -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:conf/spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
 
	<!-- session timeout -->
	<session-config>
		<session-timeout>30</session-timeout>
	</session-config>
 
</web-app>

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";
	}
}
•


总结

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值