最近将redis整合到项目中,将redis作为cache使用,未来进一步作为消息推送使用。我通过jedis和spring配置实现操作redis。

spring配置

    <!-- redis配置 -->
<context:property-placeholder location="classpath:setup/redis.properties" /> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.pool.maxTotal}"></property>
<property name="maxIdle" value="${redis.pool.maxIdle}"></property>
<property name="minIdle" value="${redis.pool.minIdle}"></property>
<property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}"></property>
<property name="minEvictableIdleTimeMillis" value="${redis.pool.minEvictableIdleTimeMillis}"></property>
<property name="numTestsPerEvictionRun" value="${redis.pool.numTestsPerEvictionRun}"></property>
<property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"></property>
</bean> <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" scope="singleton" >
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<bean name="master" class="redis.clients.jedis.JedisShardInfo">
<constructor-arg name="host" index="0" value="${redis.host}" />
<constructor-arg name="port" index="1" value="${redis.port}" type="int"/>
<constructor-arg name="timeout" index="2" value="${redis.timeout}" type="int"/>
</bean>
</list>
</constructor-arg>
</bean>

我们可以将redis相关配置信息单独成redis.properties文件,然后通过context:property-placeholder进行扫描,可以通过spring类似el方式注解参数。

我们同时还可以通过制定scope属性,配置为单例模式

    scope="singleton"

网上的关于JedisShardInfo的构造器配置是旧版本的。如果参数个数不正确会提示

    Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

同时构造器的参数名称必须与构造器的参数保持一致,否则会提示以下错误信息

    Unsatisfied dependency expressed through constructor argument with index 0 of type [java.lang.String]:
Ambiguous constructor argument types - did you specify the correct bean references as constructor arguments?

jedis 2.7.2中的JedisShardInfo提供了以下几个构造方法

    public JedisShardInfo(String host)
public JedisShardInfo(String host, String name)
public JedisShardInfo(String host, int port)
public JedisShardInfo(String host, int port, String name)
public JedisShardInfo(String host, int port, int timeout)
public JedisShardInfo(String host, int port, int timeout, String name)
public JedisShardInfo(String host, int port, int connectionTimeout, int soTimeout, int weight)
public JedisShardInfo(String host, String name, int port, int timeout, int weight)
public JedisShardInfo(URI uri)
  • redis.properties配置内容如下
#IP
redis.host=59.56.74.73
#Port
redis.port=25879
#客户端请求超时时间,单位毫秒
redis.timeout=20000
#访问密码,默认没有密码
redis.password=
#默认的数据库索引号
redis.database=0
#是否使用池
redis.usePool=true #jedis的pool最多可管理的jedis实例
redis.pool.maxTotal=1024
#最大的空闲jedis实例
redis.pool.maxIdle=200
#最小空闲jedis实例
redis.pool.minIdle=0
#当池内没有返回对象时,最大等待时间,设置为10s
redis.pool.maxWaitMillis=10000
#当调用borrow Object方法时,是否进行有效性检查
redis.pool.testOnBorrow=true
#当调用return Object方法时,是否进行有效性检查
redis.pool.testOnReturn=true #testWhileIdle:如果为true,表示有一个idle object evitor线程对idle object进行扫描,如果validate失败,此object会被从pool中drop掉;
#这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义;
redis.pool.testWhileIdle=true
#表示一个对象至少停留在idle状态的最短时间,然后才能被idle object evitor扫描并驱逐;
#这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义;
redis.pool.minEvictableIdleTimeMillis=300000
#表示idle object evitor每次扫描的最多的对象数
redis.pool.numTestsPerEvictionRun=3
#表示idle object evitor两次扫描之间要sleep的毫秒数
redis.pool.timeBetweenEvictionRunsMillis=60000

我的jedis版本为2.7.2,因此网上的很多maxactive和maxwait参数已经改为maxtotal和maxWaitMillis。同时jedis 2.7.2使用的是commom-pool 2版本。common-pool2的一些方法已经改变。

redis类实现

/**
* key = product:module:identity
* */
public class Redis {
private final static Logger logger = LoggerFactory.getLogger(Redis.class); private static ShardedJedisPool shardedJedisPool; private ShardedJedis shardedJedis; static{
if(shardedJedisPool == null){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:setup/applicationContext.xml");
shardedJedisPool = (ShardedJedisPool) context.getBean("shardedJedisPool");
}
} /*获取sharedJedis对象*/
private void getResource(){
shardedJedis = shardedJedisPool.getResource();
logger.info("__________________获取sharedJedis");
} /*释放sharedJedis对象*/
private void returnResource(){
shardedJedisPool.returnResourceObject(shardedJedis); logger.info("__________________释放sharedJedis");
} /*判断是否存在*/
private boolean existsKey(String key){
if(key != null && key.trim().length() > 0){
return shardedJedis.exists(key);
}else{
return false;
}
} /*设置value*/
public void setValue(String key, String value){
try{
getResource(); if(existsKey(key)){
shardedJedis.set(key, value);
}else{
/*若key不存在,则插入该key记录*/
shardedJedis.setnx(key, value);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*key中追加value值*/
public void appendValue(String key, String value){
try{
getResource(); if(existsKey(key)){
shardedJedis.append(key, value);
}else{
shardedJedis.setnx(key, value);
} }catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*设定含有有效期限的value,单位为秒*/
public void setexValue(String key, String value, int exprise){
try{
getResource(); if(key != null && key.trim().length() > 0){
shardedJedis.setex(key, exprise, value);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*读取value*/
public String getValue(String key){
try{
getResource(); if(key != null && key.trim().length() > 0){
return shardedJedis.get(key);
}else{
return null;
}
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /**获取并修改value*/
public String getSetValue(String key, String value){
try{
getResource(); if(existsKey(key)){
return shardedJedis.getSet(key, value);
}else{
setValue(key, value);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*截取指定长度的字符串*/
public String getRangeValue(String key, int start, int end){
try{
getResource(); if(key != null && key.trim().length() > 0){
return shardedJedis.getrange(key, start, end);
}else{
return null;
}
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*删除value*/
public void deleteValue(String key){
try{
getResource(); if(key != null && key.trim().length() > 0){
shardedJedis.del(key);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*list添加元素*/
public void pushListItem(String key, String value){
try{
getResource(); if(key != null && key.trim().length() > 0){
shardedJedis.lpush(key, value);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*设置list的元素值*/
public void setListItem(String key, int index, String value){
try{
getResource(); shardedJedis.lset(key, index, value);
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*返回list长度*/
public Long getListSize(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.llen(key);
} return (long) 0;
}catch(Exception e){
e.printStackTrace();
return (long) 0;
}finally{
returnResource();
}
} /*返回排序过的list*/
public List<String> getSortList(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.sort(key);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*返回指定范围的list*/
public List<String> getListItemRange(String key, int start, int end){
try{
getResource(); if(existsKey(key)){
return shardedJedis.lrange(key, start, end);
}else{
return null;
}
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*返回list指定索引的item的值*/
public String getListItemValue(String key, int index){
try{
getResource(); if(existsKey(key)){
return shardedJedis.lindex("lists", index);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*返回list指定范围的list*/
public List<String> getListRangeItems(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.lrange(key, 0, -1);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*删除list的值为value的item*/
public void delListItem(String key, int index, String value){
try{
getResource(); if(existsKey(key)){
shardedJedis.lrem(key, 1, value);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*删除list指定范围以外的item*/
public void deleteListRange(String key, int start, int end){
try{
getResource(); shardedJedis.ltrim(key, start, end);
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*list第一个item出栈, 并返回该item*/
public String getListPopItem(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.lpop(key);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*设置hashmap*/
public void setMapItem(String key, HashMap<String, String> map){
try{
getResource(); if(key != null && key.trim().length() > 0){
shardedJedis.hmset(key, map);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*返回hashmap的键个数*/
public Long getMapLength(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.hlen(key);
} return (long) 0;
}catch(Exception e){
e.printStackTrace();
return (long) 0;
}finally{
returnResource();
}
} /*返回hashmap中的所有key*/
public Set<String> getMapAllKeys(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.hkeys(key);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*返回hashmap中的所有value*/
public List<String> getMapAllValues(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.hvals(key);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*获取hashmap*/
public List<String> getMapItem(String key, String... fields){
try{
getResource(); return shardedJedis.hmget(key, fields);
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*删除map中item*/
public void deleteMapItem(String key, String itemKey){
try{
getResource(); if(existsKey(key)){
shardedJedis.hdel(key, itemKey);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*事务*/ /*管道*/ /*管道中事物*/
}

调用方法

	Redis redis = new Redis();
redis.setValue("foo", "look here"); System.out.println("____________value="+ redis.getValue("foo"));
redis.deleteValue("foo");
  • 通过注入方式实现

上面的配置信息不变,下面是注入的代码和调用的代码

/**
* key = product:module:identity
* */
@Component
public class Redis {
private final static Logger logger = LoggerFactory.getLogger(Redis.class); /*配置bean,通过注入方式获取切片连接池*/
@Resource(name="shardedJedisPool")
private ShardedJedisPool shardedJedisPool; /**
* @return the shardedJedisPool
*/
public ShardedJedisPool getShardedJedisPool() {
return shardedJedisPool;
} /**
* @param shardedJedisPool the shardedJedisPool to set
*/
public void setShardedJedisPool(ShardedJedisPool shardedJedisPool) {
this.shardedJedisPool = shardedJedisPool;
} /**
* @return the shardedJedis
*/
public ShardedJedis getShardedJedis() {
return shardedJedis;
} /**
* @param shardedJedis the shardedJedis to set
*/
public void setShardedJedis(ShardedJedis shardedJedis) {
this.shardedJedis = shardedJedis;
} private ShardedJedis shardedJedis; /*获取sharedJedis对象*/
private void getResource(){
shardedJedis = shardedJedisPool.getResource();
logger.info("__________________获取sharedJedis");
} /*释放sharedJedis对象*/
private void returnResource(){
shardedJedisPool.returnResourceObject(shardedJedis); logger.info("__________________释放sharedJedis");
} /*判断是否存在*/
private boolean existsKey(String key){
if(key != null && key.trim().length() > 0){
return shardedJedis.exists(key);
}else{
return false;
}
} /*设置value*/
public void setValue(String key, String value){
try{
getResource(); if(existsKey(key)){
shardedJedis.set(key, value);
}else{
/*若key不存在,则插入该key记录*/
shardedJedis.setnx(key, value);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*key中追加value值*/
public void appendValue(String key, String value){
try{
getResource(); if(existsKey(key)){
shardedJedis.append(key, value);
}else{
shardedJedis.setnx(key, value);
} }catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*设定含有有效期限的value,单位为秒*/
public void setexValue(String key, String value, int exprise){
try{
getResource(); if(key != null && key.trim().length() > 0){
shardedJedis.setex(key, exprise, value);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*读取value*/
public String getValue(String key){
try{
getResource(); if(key != null && key.trim().length() > 0){
return shardedJedis.get(key);
}else{
return null;
}
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /**获取并修改value*/
public String getSetValue(String key, String value){
try{
getResource(); if(existsKey(key)){
return shardedJedis.getSet(key, value);
}else{
setValue(key, value);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*截取指定长度的字符串*/
public String getRangeValue(String key, int start, int end){
try{
getResource(); if(key != null && key.trim().length() > 0){
return shardedJedis.getrange(key, start, end);
}else{
return null;
}
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*删除value*/
public void deleteValue(String key){
try{
getResource(); if(key != null && key.trim().length() > 0){
shardedJedis.del(key);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*list添加元素*/
public void pushListItem(String key, String value){
try{
getResource(); if(key != null && key.trim().length() > 0){
shardedJedis.lpush(key, value);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*设置list的元素值*/
public void setListItem(String key, int index, String value){
try{
getResource(); shardedJedis.lset(key, index, value);
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*返回list长度*/
public Long getListSize(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.llen(key);
} return (long) 0;
}catch(Exception e){
e.printStackTrace();
return (long) 0;
}finally{
returnResource();
}
} /*返回排序过的list*/
public List<String> getSortList(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.sort(key);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*返回指定范围的list*/
public List<String> getListItemRange(String key, int start, int end){
try{
getResource(); if(existsKey(key)){
return shardedJedis.lrange(key, start, end);
}else{
return null;
}
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*返回list指定索引的item的值*/
public String getListItemValue(String key, int index){
try{
getResource(); if(existsKey(key)){
return shardedJedis.lindex("lists", index);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*返回list指定范围的list*/
public List<String> getListRangeItems(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.lrange(key, 0, -1);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*删除list的值为value的item*/
public void delListItem(String key, int index, String value){
try{
getResource(); if(existsKey(key)){
shardedJedis.lrem(key, 1, value);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*删除list指定范围以外的item*/
public void deleteListRange(String key, int start, int end){
try{
getResource(); shardedJedis.ltrim(key, start, end);
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*list第一个item出栈, 并返回该item*/
public String getListPopItem(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.lpop(key);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*设置hashmap*/
public void setMapItem(String key, HashMap<String, String> map){
try{
getResource(); if(key != null && key.trim().length() > 0){
shardedJedis.hmset(key, map);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*返回hashmap的键个数*/
public Long getMapLength(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.hlen(key);
} return (long) 0;
}catch(Exception e){
e.printStackTrace();
return (long) 0;
}finally{
returnResource();
}
} /*返回hashmap中的所有key*/
public Set<String> getMapAllKeys(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.hkeys(key);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*返回hashmap中的所有value*/
public List<String> getMapAllValues(String key){
try{
getResource(); if(existsKey(key)){
return shardedJedis.hvals(key);
} return null;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*获取hashmap*/
public List<String> getMapItem(String key, String... fields){
try{
getResource(); return shardedJedis.hmget(key, fields);
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
returnResource();
}
} /*删除map中item*/
public void deleteMapItem(String key, String itemKey){
try{
getResource(); if(existsKey(key)){
shardedJedis.hdel(key, itemKey);
}
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource();
}
} /*事务*/ /*管道*/ /*管道中事物*/
}

调用方法

	@Resource
Redis redis;
        redis.setValue("foo", "look here");
                
        System.out.println("____________value="+ redis.getValue("foo"));
        redis.deleteValue("foo");

jedis应用实例的更多相关文章

  1. spring集成jedis简单实例

    jedis是redis的java客户端,spring将redis连接池作为一个bean配置. redis连接池分为两种,一种是“redis.clients.jedis.ShardedJedisPool ...

  2. jedis入门实例

    在使用传统的关系数据库,我们都需要依赖一个所谓的实现了jdbc规范的驱动程序来连接数据库,这些驱动程序由各大数据库厂商提供.这些驱动就是jar包,里面就是封装了对数据库的通信协议,我们通过简单的调用就 ...

  3. 峰Redis学习(2)Jedis 入门实例

    参考博客:http://blog.java1234.com/blog/articles/314.html 第一节:使用Jedis 连接Redis 新建maven项目: pom.xml: <pro ...

  4. Redis + Jedis + Spring 实例(对象的操作)

        目录(?)[+] 不得不说,用哈希操作来存对象,有点自讨苦吃! 不过,既然吃了苦,也做个记录,也许以后API升级后,能好用些呢?! 或许,是我的理解不对,没有真正的理解哈希表. 一.预期 接上 ...

  5. Java中使用Jedis操作Redis(转载)

    整理 1.字符串 添加:set keyname value 查询:get keyname 拼接:append keyname value 删除:del keyname 添加多个: mset keyna ...

  6. JedisPool异常Jedis链接处理

    问题现象(jedis-2.1.0.jar) 基于JedisPool管理Jedis对象,通过get方法获取值,出现key对应的value值错误,例如: K V a a b b Jedis.get(“a” ...

  7. Redis客户端开发包:Jedis学习-入门

    添加Jedis依赖 我们可以使用以下三种方式来添加Jedis依赖. 1.下载jar文件 从http://search.maven.org/下载最近的jedis包和Apache Commons Pool ...

  8. jedis操作redis全指南

    package com.wujintao.redis; import java.util.Date; import java.util.HashMap; import java.util.Iterat ...

  9. [redis] redis 存取键值对常用的三种使用方式 - Jedis、JedisPool、Jedis分布式

    |-Jedis 普通方式 |-JedisPool 连接池方式(需要引入pool相关jar) |-Jedis 分布式 (需要引入pool相关jar) 引入jedis2.7.0和commons.pool2 ...

随机推荐

  1. bzoj1797

    其实我觉得这种题目风格很像今天省选第三轮D1T1 都是在一个算法模型上去探索规律: 首先我们要做一遍最大流毫无疑问 第一问看起来很好想,只要是满流边就可以了? 错,反例不难找到 如:1--->2 ...

  2. bzoj1821

    题目要求最近的两个部落间距尽可能最远 不难想到一种贪心的方法,对每两个点之间距离从小到大排序, 把每个点看成一个部落 然后不断将距离近的两个部落合并成一个部落,直到剩下了k个部落,那么下一条不同部落之 ...

  3. C#中的try catch finally

    try中的程序块是有可能发生错误的程序块,catch中的程序块是当发生错误的时候才会执行的代码块,finally中的程序块是无论是否发生错误都会执行的代码块. 示例程序: ? 1 2 3 4 5 6 ...

  4. Azure 媒体服务支持 DASH 实时传送流

    Kilroy Hughes Azure媒体服务数字媒体架构师 本文重点介绍 Azure 媒体服务支持的 DASH 实时传送流功能,同时阐述如何利用这些功能将实时和点播自适应流传送至 Web 浏览器 ...

  5. POJ 3159 Candies 差分约束dij

    分析:设每个人的糖果数量是a[i] 最终就是求a[n]-a[1]的最大值 然后给出m个关系 u,v,c 表示a[u]+c>=a[v] 就是a[v]-a[u]<=c 所以对于这种情况,按照u ...

  6. Red5 1.0.5安装过程记录

    Red5从旧的服务器切换到了github上后,截至20150702仍未更新文档.为了搭建Red5开发环境,我像无头苍蝇一样乱转了很多博客和StackOverflow.藉此记录这次安装过程,希望能够帮助 ...

  7. SSAS数据挖掘算法简介

    决策树分析算法:以二叉树的形式展现,分析出影响某种行为(如购买自行车)的因素,并对这些因素排序. 聚类分析算法:物以类聚,人以群分.分析特定群体所共同含有的属性(因素). 未完,待续..

  8. POJ-2442 Sequence K路归并问题

    题目链接:http://poj.org/problem?id=2442 问题一:K个有序表合成一个有序表,元素共有n个.用堆优化 问题二:两个序列的前n小的元素.堆优化. 这题就是问题二的扩展,每次处 ...

  9. 【面试虐菜】—— MongoDB知识整理

    为什么我们要使用MongoDB? 特点: 高性能.易部署.易使用,存储数据非常方便.主要功能特性有: 面向集合存储,易存储对象类型的数据. 模式自由. 支持动态查询. 支持完全索引,包含内部对象. 支 ...

  10. Spring Bean Scope 有状态的Bean 无状态的Bean

    http://blog.csdn.net/anyoneking/article/details/5182164 在Spring的Bean配置中,存在这样两种情况: <bean id=" ...