package com.xx.redis;
import java.util.List;
import java.util.ResourceBundle;
import com.alibaba.fastjson.JSON;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisClient {
public static JedisPool jedisPool; // 池化管理jedis链接池
static {
// 读取相关的配置:redis.properties
ResourceBundle resourceBundle = ResourceBundle.getBundle("redis");
int maxActive = Integer.parseInt(resourceBundle.getString("redis.pool.maxActive"));
int maxIdle = Integer.parseInt(resourceBundle.getString("redis.pool.maxIdle"));
int maxWait = Integer.parseInt(resourceBundle.getString("redis.pool.maxWait"));
String ip = resourceBundle.getString("redis.ip");
int port = Integer.parseInt(resourceBundle.getString("redis.port"));
JedisPoolConfig config = new JedisPoolConfig();
// 设置最大连接数
config.setMaxTotal(maxActive);
// 设置最大空闲数
config.setMaxIdle(maxIdle);
// 设置超时时间
config.setMaxWaitMillis(maxWait);
// 初始化连接池
jedisPool = new JedisPool(config, ip, port);
}
/**
* 向缓存中设置字符串内容
*
* @param key
* key
* @param value
* value
* @return
* @throws Exception
*/
public static boolean set(String key, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
jedisPool.returnResource(jedis);
}
}
/**
* 向缓存中设置对象
*
* @param key
* @param value
* @return
*/
public static boolean set(String key, Object value) {
Jedis jedis = null;
try {
String objectJson = JSON.toJSONString(value);
jedis = jedisPool.getResource(); // 从池中获取一个Jedis对象
jedis.set(key, objectJson);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
jedisPool.returnResource(jedis);//释放对象池
}
}
/**
* 删除缓存中得对象,根据key
*
* @param key
* @return
*/
public static boolean del(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.del(key);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
jedisPool.returnResource(jedis);
}
}
/**
* 根据key 获取内容
*
* @param key
* @return
*/
public static Object get(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Object value = jedis.get(key);
return value;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
jedisPool.returnResource(jedis);
}
}
/**
* 根据key 获取对象
*
* @param key
* @return
*/
public static T get1(String key, Class clazz) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String value = jedis.get(key);
return JSON.parseObject(value, clazz);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
jedisPool.returnResource(jedis);
}
}
/**
* 根据key 获取对象
*
* @param key
* @return
*/
public static String getStr(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
jedisPool.returnResource(jedis);
}
}
/**
* 根据key 获取对象
*
* @param key
* @return
*/
public static List getList(String key, Class clazz) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String value = jedis.get(key);
return JSON.parseArray(value, clazz);
} catch (Exception e) {
// e.printStackTrace();
return null;
} finally {
try {
jedisPool.returnResource(jedis);
} catch (Exception e) {
System.out.println("");
}
}
}
public static void flushAll() {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.flushAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
jedisPool.returnResource(jedis);
}
}
}
redis.properties
redis.pool.maxActive=100
redis.pool.maxIdle=20
redis.pool.maxWait=3000
redis.ip=localhost
redis.port=6379
<dependency>
<groupId>net.sf.json-libgroupId>
<artifactId>json-libartifactId>
<version>2.4version>
<classifier>jdk15classifier>
dependency>
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
<version>2.6.2version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.12version>
dependency>
===================
另外一种实现:
package cache.redis;
/**
* @Description: RedisTemplate匿名内部类接口
* @author fanmintao
* @date 2017年1月3日
*/
public interface Function {
public T execute(E e);
}
package cache.redis;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import utils.FastJsonUtils;
/**
* @Description:redis使用的封装类
* @author fanmintao
* @date 2017年1月3日
*/
@Component
public class RedisTemplate {
private static Logger log = Logger.getLogger(RedisTemplate.class);
// 有的工程需要,有的工程不需要。设置required=false,有就注入,没有就不注入。
@Autowired(required = false)
private ShardedJedisPool shardedJedisPool;
private T execute(Function function) {
ShardedJedis shardedJedis = null;
try {
// 从连接池中获取到jedis分片对象
shardedJedis = shardedJedisPool.getResource();
return function.execute(shardedJedis);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != shardedJedis) {
// 关闭,检测连接是否有效,有效则放回到连接池中,无效则重置状态
shardedJedis.close();
}
}
return null;
}
/**
* 直接保存对象到redis中
*
* @param key
* @param obect
* @return
*/
public String set(final String key, final Object object) {
return this.execute(new Function() {
@Override
public String execute(ShardedJedis shardedJedis) {
String result=null;
try {
result=shardedJedis.set(key, FastJsonUtils.obj2json(object));
} catch (Exception e) {
log.error("保存对象到redis中发生异常",e);
}
return result;
}
});
}
/**
* 保存数据到redis中,生存时间单位是:秒
*
* @param key
* @param value
* @param seconds
* @return
*/
public String set(final String key, final Object object, final Integer seconds) {
return this.execute(new Function() {
@Override
public String execute(ShardedJedis shardedJedis) {
String result = set(key, object);
shardedJedis.expire(key, seconds);// 设置生存时间
return result;
}
});
}
/**
* 从redis中获取数据
*
* @param key
* @return
*/
public String get(final String key) {
return this.execute(new Function() {
@Override
public String execute(ShardedJedis shardedJedis) {
String result=null;
try {
result=shardedJedis.get(key);
} catch (Exception e) {
log.error("从redis中获取数据发生异常",e);
}
return result;
}
});
}
/**
* 从redis中直接获取缓存对象
*
* @param key
* @return
*/
public T get(String key, Class clazz) {
String text = get(key);
T result = null;
try {
result = FastJsonUtils.json2obj(text, clazz);
} catch (Exception e) {
log.error("从redis中直接获取缓存对象发生错误",e);
}
return result;
}
public Map getMap(String key, Class clazz) {
String jsonStr = get(key);
Map result = null;
try {
result = FastJsonUtils.json2map(jsonStr, clazz);
} catch (Exception e) {
log.error("从redis中直接获取缓存对象发生错误",e);
}
return result;
}
/**
* 设置key生存时间,单位:秒
*
* @param key
* @param seconds
* @return
*/
public Long expire(final String key, final Integer seconds) {
return this.execute(new Function() {
@Override
public Long execute(ShardedJedis shardedJedis) {
Long result=null;
try {
result=shardedJedis.expire(key, seconds);
} catch (Exception e) {
log.error("设置key生存时间发生错误",e);
}
return result;
}
});
}
/**
* 从redis中删除数据
*
* @param key
* @return
*/
public Long del(final String key) {
return this.execute(new Function() {
@Override
public Long execute(ShardedJedis shardedJedis) {
Long result=null;
try {
result=shardedJedis.del(key);
} catch (Exception e) {
log.error("从redis中删除数据发生错误",e);
}
return result;
}
});
}
/**
* 判断key值是否存在
*
* @param key
* @return
*/
public Boolean exists(final String key) {
return this.execute(new Function() {
@Override
public Boolean execute(ShardedJedis shardedJedis) {
Boolean result=false;
try {
result=shardedJedis.exists(key);
} catch (Exception e) {
log.error("判断key值是否存在发生错误",e);
}
return result;
}
});
}
/**
* 保存Hash数据到redis
*
* @param key field result
* @return
*/
public Long hset(final String key, final String field, final Object object) {
return this.execute(new Function() {
public Long execute(ShardedJedis shardedJedis) {
Long result=null;
try {
result=shardedJedis.hset(key, field, FastJsonUtils.obj2json(object));
} catch (Exception e) {
log.error("保存Hash数据到redis发生错误",e);
}
return result;
}
});
}
/**
* 设置Hash的缓存过期时间
*
* @param key field result
* @return
*/
public Long hset(final String key, final String field, final Object object,final Integer seconds) {
return this.execute(new Function() {
public Long execute(ShardedJedis shardedJedis) {
Long result=null;
try {
result=hset(key, field, object);
shardedJedis.expire(key, seconds);
} catch (Exception e) {
log.error("设置Hash的缓存过期时间发生错误",e);
}
return result;
}
});
}
/**
* 从redis中获取Hash数据
*
* @param key
* @param field
* @return
*/
public String hget(final String key, final String field) {
return this.execute(new Function() {
@Override
public String execute(ShardedJedis shardedJedis) {
String result=null;
try {
result=shardedJedis.hget(key, field);
} catch (Exception e) {
log.error("从redis中获取Hash数据发生错误",e);
}
return result;
}
});
}
/**
* 从redis中删除Hash数据
*
* @param key
* @param field
* @return
*/
public Long hdel(final String key, final String field) {
return this.execute(new Function() {
@Override
public Long execute(ShardedJedis shardedJedis) {
Long result=null;
try {
result=shardedJedis.hdel(key, field);
} catch (Exception e) {
log.error("从redis中删除Hash数据发生错误",e);
}
return result;
}
});
}
/**
* 从redis中获取Hash数据直接返回对象
*
* @param
* @param key
* @param field
* @param clazz
* @return
*/
public T hget(String key, String field, Class clazz) {
String text = hget(key, field);
T result = null;
try {
result = FastJsonUtils.json2obj(text, clazz);
} catch (Exception e) {
log.error("从redis中获取Hash数据直接返回对象发生错误",e);
}
return result;
}
/**
* 判断key与field(hashKey)是否存在
*
* @param key
* @param field
* @return
*/
public Boolean hexists(final String key,final String field) {
return this.execute(new Function() {
public Boolean execute(ShardedJedis shardedJedis) {
Boolean result=false;
try {
result=shardedJedis.hexists(key, field);
} catch (Exception e) {
log.error("判断key与field(hashKey)是否存在发生错误",e);
}
return result;
}
});
}
}
package utils;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
/**
* fastjson utils
*
* @author magic_yy
* @see https://github.com/alibaba/fastjson
* @see http://code.alibabatech.com/wiki/display/FastJSON
*/
public class FastJsonUtils {
private static SerializeConfig mapping = new SerializeConfig();
static{
mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
}
/**
* javaBean、list、map convert to json string
*/
public static String obj2json(Object obj){
// return JSON.toJSONString(obj,SerializerFeature.UseSingleQuotes);//使用单引号
// return JSON.toJSONString(obj,true);//格式化数据,方便阅读
return JSON.toJSONString(obj,mapping);
}
/**
* json string convert to javaBean、map
*/
public static T json2obj(String jsonStr,Class clazz){
return JSON.parseObject(jsonStr,clazz);
}
/**
* json array string convert to list with javaBean
*/
public static List json2list(String jsonArrayStr,Class clazz){
return JSON.parseArray(jsonArrayStr, clazz);
}
/**
* json string convert to map
*/
public static Map json2map(String jsonStr){
return json2obj(jsonStr, Map.class);
}
/**
* json string convert to map with javaBean
*/
public static Map json2map(String jsonStr,Class clazz){
Map map = JSON.parseObject(jsonStr, new TypeReference
redis.maxTotal=50
redis.maxIdle=8
redis.maxWait=1000
redis.testOnBorrow=true
redis.timeout=100000
redis.node1.ip=192.168.85.5
redis.node1.port=6380
#redis.node2.ip=192.168.163.100
#redis.node2.port=6380
#redis.node3.ip=192.168.163.101
#redis.node3.port=6379
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">
<context:component-scan base-package="cache"/>
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.maxTotal}" />
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
bean>
<bean id="jedisShardInfo1" class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="${redis.node1.ip}" />
<constructor-arg index="1" value="${redis.node1.port}" />
<constructor-arg index="2" value="${redis.timeout}" />
bean>
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool"
destroy-method="close">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<ref bean="jedisShardInfo1" />
list>
constructor-arg>
bean>
beans>