Jedis+spring集成
来源:互联网 发布:p站软件 编辑:程序博客网 时间:2024/05/01 20:44
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:
<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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://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 settingsredis.host=127.0.0.1redis.port=6379redis.timeout=3000#redis.pass= redis.maxIdle=300redis.maxActive=600redis.maxWait=1000redis.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; @Componentpublic 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; @Controllerpublic class RedisController {@Autowiredprivate JedisUtil jedisUtil; /** * * @param str * @return * @throws InterruptedException */@RequestMapping(value="/redis", method={RequestMethod.POST,RequestMethod.GET})public String redis(String str) throws InterruptedException{ //用户idString 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 0
- spring集成jedis
- Spring 集成jedis
- Jedis+spring集成
- Spring Jedis集成Redis
- Spring + Jedis集成Redis
- Spring 集成 Jedis
- Spring与Jedis的集成
- 使用Spring + Jedis集成Redis
- Spring与Jedis的集成
- 使用Spring + Jedis集成Redis
- 使用Spring + Jedis集成Redis
- spring集成Jedis Cluster配置
- Spring boot上集成Jedis
- spring中集成使用jedis(1)
- spring中集成使用jedis(2)
- netty里集成spring注入jedis
- spring集成jedis支持redis3.0集群
- redis -Spring与Jedis的集成
- OpenStack 使用Ceph 配置指导
- SpringMvc控制层之间的带参数访问
- 如何正确的初始化
- Redis持久化实践及灾难恢复模拟
- Spring MVC 教程,快速入门,深入分析
- Jedis+spring集成
- 极客以折腾不息的树莓派玩法
- HDU 2141 Can you find it?(暴力+二分)
- UIImagePickerController简单使用
- mongodb 常用查询语句整理
- hdu 2093 考试排名
- [ZJOI2014][JZOJ3617]力
- 多线程死锁问题
- Merkel Under Pressure After Migrant Influx