参考了各位大神的文章,忘记出自哪里了,记录一下在代码里面的实现
controller层
@Autowired
private RedisCacheStorageService<String, CheckInOutVo> redisCacheStorage; //写入 读取序列化
@RequestMapping(value = "/goCsdy.do", method = RequestMethod.POST)
@ResponseBody // redis 测试
public void goCsdy1() throws Exception {
//
// System.out.println("开始执行测试"); //单条数据写入
// CheckInOutVo checkInOutVo = new CheckInOutVo(); //对象
// checkInOutVo.setUserName("刘德华");
// checkInOutVo.setAmup("5895");
// checkInOutVo.setAmtout("123131");
// String redisKey="checkInOutVo:UserName:123:2622";
// redisCacheStorage.set(redisKey, checkInOutVo); //对象转
// CheckInOutVo checkInOutVo2 = redisCacheStorage.get(redisKey, new CheckInOutVo());
// System.out.println("======="+checkInOutVo2.getUserName()+"====="+checkInOutVo2.getAmup()+"====="+checkInOutVo2.getAmtout());
///
// 删除或者批量添加
//
// ShardedJedis jedis = getShardedJedis();
// ShardedJedisPipeline pipeline = jedis.pipelined();
// long begin = System.currentTimeMillis();
// for (int i = 0; i < count; i++) {
// String redisKey="checkInOutVo:UserName:"+"刘德华:"+i;
CheckInOutVo checkInOutVo = new CheckInOutVo();
checkInOutVo.setUserName("刘德华");
checkInOutVo.setAmup("5895");
checkInOutVo.setAmtout("123131"+i);
JSONObject json = JSONObject.fromObject(checkInOutVo);//将java对象转换为json对象
String jsonValue = json.toString();//将json对象转换为json字符串
pipeline.set(redisKey, jsonValue);
pipeline.del(redisKey);
// }
// pipeline.sync();
// jedis.close();
// System.out.println("usePipeline total time:" + (System.currentTimeMillis() - begin));
///
// 批量读取
///
ShardedJedis jedis = getShardedJedis();
ShardedJedisPipeline pipeline = jedis.pipelined();
long begin = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
String redisKey="checkInOutVo:UserName:"+"刘德华:"+i;
CheckInOutVo checkInOutVo2 = redisCacheStorage.get(redisKey, new CheckInOutVo());
System.out.println("======="+checkInOutVo2.getUserName()+"====="+checkInOutVo2.getAmup()+"====="+checkInOutVo2.getAmtout());
}
pipeline.sync();
jedis.close();
System.out.println("usePipeline total time:" + (System.currentTimeMillis() - begin));
///
}
private static int count = 10000;
public static ShardedJedis getShardedJedis() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(2);
poolConfig.setMaxIdle(1);
poolConfig.setMaxWaitMillis(2000);
poolConfig.setTestOnBorrow(false);
poolConfig.setTestOnReturn(false);
JedisShardInfo info1 = new JedisShardInfo("127.0.0.1", 6379);
JedisShardInfo info2 = new JedisShardInfo("127.0.0.1", 6379);
ShardedJedisPool pool = new ShardedJedisPool(poolConfig, Arrays.asList(info1, info2));
return pool.getResource();
}
RedisCacheStorageService 序列号类
package com.wxyding.service;
import java.util.Map;
/**
* Created by ${HeJD} on 2018/6/29.
*/
public interface RedisCacheStorageService<K,V> {
/**
* 在redis数据库中插入 key 和value
* @param key
* @param value
* @return
*/
boolean set(K key,V value);
/**
* 在redis数据库中插入 key 和value 并且设置过期时间
* @param key
* @param value
* @param exp 过期时间
* @return
*/
boolean set(K key, V value, int exp);
/**
* 根据key 去redis 中获取value
* @param key
* @return
*/
V get(K key,Object object);
/**
* 删除redis库中的数据
* @param key
* @return
*/
boolean remove(K key);
/**
* 设置哈希类型数据到redis 数据库
* @param cacheKey 可以看做一张表
* @param key 表字段
* @param value
* @return
*/
boolean hset(String cacheKey,K key,V value);
/**
* 获取哈希表数据类型的值
* @param cacheKey
* @param key
* @return
*/
V hget(String cacheKey,K key,Object object);
/**
* 获取哈希类型的数据
* @param cacheKey
* @return
*/
Map<K,V> hget(String cacheKey,Object object);
}
RedisCacheStorageServiceImpl序列号转对象实现层
package com.wxyding.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.wxyding.service.RedisCacheStorageService;
import com.wxyding.util.RedisUtil;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisException;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by ${HeJD} on 2018/6/29.
*/
@Service("redisCacheStorageService")
public class RedisCacheStorageServiceImpl<V> implements RedisCacheStorageService<String,V>{
private Logger log= LoggerFactory.getLogger(RedisCacheStorageServiceImpl.class);
/**
* 默认过时时间
*/
private static final int EXPRIE_TIME =3600*24;
/**
* 获取Jedis相关操作
*/
@Autowired
private RedisUtil redisUtil;
@Override
public boolean set(String key, V value) {
return set(key,value,EXPRIE_TIME);
}
@Override
public boolean set(String key, V value, int exp) {
Jedis jedis=null;
if(StringUtils.isEmpty(key)){
return false;
}
try {
//获取jedis对象
jedis= redisUtil.getResource();
//使用对象转换为Json格式插入redis
JSONObject json = JSONObject.fromObject(value);//将java对象转换为json对象
String jsonValue = json.toString();//将json对象转换为json字符串
jedis.setex(key,exp,jsonValue);
}catch (Exception e){
//释放jedis对象
redisUtil.brokenResource(jedis);
log.info("client can't connect server");
return false;
}finally {
//返还连接池
redisUtil.returnResource(jedis);
return true;
}
}
@Override
public V get(String key,Object object) {
Jedis jedis=null;
V v=null;
if(StringUtils.isEmpty(key)){
log.info("redis取值,key为空");
return null;
}
try{
jedis=redisUtil.getResource(); //获取连接
String jsonValue=jedis.get(key); //从redis得到值,得到的是json字符串,因为我们之前插入的时候是使用的json字符串
if(StringUtils.isEmpty(jsonValue)){
return null;
}
JSONObject obj = new JSONObject().fromObject(jsonValue);//将json字符串转换为json对象
v = (V)JSONObject.toBean(obj,object.getClass());//将建json对象转换为你想要的java对象
return v;
}catch (Exception e){
//释放jedis对象
if(jedis!=null){
redisUtil.brokenResource(jedis);
}
log.info("client can't get value");
return null;
}finally {
//返还连接池
redisUtil.returnResource(jedis);
}
}
@Override
public boolean remove(String key) {
Jedis jedis=null;
try{
jedis=redisUtil.getResource();
if(StringUtils.isEmpty(key)){
log.info("redis取值,key为空");
return false;
}
jedis.del(key);
}catch (Exception e) {
//释放jedis对象
if(jedis!=null){
redisUtil.brokenResource(jedis);
}
log.info(" del fail from redis");
return false;
}finally{
//返还连接池
redisUtil.returnResource(jedis);
return true;
}
}
@Override
public boolean hset(String cacheKey, String key, V value) {
Jedis jedis =null;
//将key 和value 转换成 json 对象
JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象
String jCacheKey = json.toString();//将json对象转换为json字符串
JSONObject json2 = JSONObject.fromObject(value);//将java对象转换为json对象
String jsonValue = json2.toString();//将json对象转换为json字符串
//操作是否成功
boolean isSucess =true;
if(StringUtils.isEmpty(jCacheKey)){
log.info("cacheKey is empty");
return false;
}
try {
jedis =redisUtil.getResource();
//执行插入哈希
jedis.hset(jCacheKey, key, jsonValue);
} catch (Exception e) {
log.info("client can't connect server");
isSucess =false;
if(null !=jedis){
//释放jedis 对象
redisUtil.brokenResource(jedis);
}
return false;
}finally{
if (isSucess) {
//返还连接池
redisUtil.returnResource(jedis);
}
return true;
}
}
@Override
public V hget(String cacheKey, String key,Object object) {
Jedis jedis =null;
V v =null;
JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象
String jCacheKey = json.toString();//将json对象转换为json字符串
if(StringUtils.isEmpty(jCacheKey)){
log.info("cacheKey is empty");
return null;
}
try {
//获取客户端对象
jedis =redisUtil.getResource();
//执行查询
String jsonValue = jedis.hget(jCacheKey, key);
//判断值是否非空
if(StringUtils.isEmpty(jsonValue)){
return null;
}else{
JSONObject obj = new JSONObject().fromObject(jsonValue);//将json字符串转换为json对象
v = (V)JSONObject.toBean(obj,object.getClass());//将建json对象转换为java对象
}
//返还连接池
redisUtil.returnResource(jedis);
} catch (JedisException e) {
log.info("client can't connect server");
if(null !=jedis){
//redisUtil 对象
redisUtil.brokenResource(jedis);
}
}
return v;
}
@Override
public Map<String, V> hget(String cacheKey,Object object) {
JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象
String jCacheKey = json.toString();//将json对象转换为字符串
//非空校验
if(StringUtils.isEmpty(jCacheKey)){
log.info("cacheKey is empty!");
return null;
}
Jedis jedis =null;
Map<String,V> result =null;
V v=null;
try {
jedis =redisUtil.getResource();
//获取列表集合 因为插入redis的时候是jsonString格式,所以取出来key是String value也是String
Map<String,String> map = jedis.hgetAll(jCacheKey);
if(null !=map){
for(Map.Entry<String, String> entry : map.entrySet()){
if(result ==null){
result =new HashMap<String,V>();
}
JSONObject obj = new JSONObject().fromObject(entry.getValue());//将json字符串转换为json对象
v = (V)JSONObject.toBean(obj,object.getClass());//将建json对象转换为java对象
result.put(entry.getKey(), v);
}
}
} catch (JedisException e) {
log.info("client can't connect server");
if(null !=jedis){
//释放jedis 对象
redisUtil.brokenResource(jedis);
}
}
return result;
}
}
RedisUtil工具类
package com.wxyding.util;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import org.slf4j.Logger;
/**
* Created by ${HeJD} on 2018/6/29.
*/
@Component
public class RedisUtil {
/**
* 日志记录
*/
private static final Logger LOG = LoggerFactory.getLogger(RedisUtil.class);
/**
* redis 连接池,这里jedisPool我们再之前spring配置中配置好了,交给spring管理,这里可以自动注入
*/
@Autowired
private JedisPool jedisPool;
public void setPool(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
/**
* 获取jedis
* @return
*/
public Jedis getResource(){
Jedis jedis =null;
try {
jedis =jedisPool.getResource();
} catch (Exception e) {
LOG.info("can't get the redis resource");
}
return jedis;
}
/**
* 关闭连接
* @param jedis
*/
public void disconnect(Jedis jedis){
jedis.disconnect();
}
/**
* 将jedis 返还连接池
* @param jedis
*/
public void returnResource(Jedis jedis){
if(null != jedis){
try {
jedisPool.returnResource(jedis);
} catch (Exception e) {
LOG.info("can't return jedis to jedisPool");
}
}
}
/**
* 无法返还jedispool,释放jedis客户端对象,
* @param jedis
*/
public void brokenResource(Jedis jedis){
if (jedis!=null) {
try {
jedisPool.returnBrokenResource(jedis);
} catch (Exception e) {
LOG.info("can't release jedis Object");
}
}
}
}
spring配置
<context:property-placeholder location="classpath:redis.properties" file-encoding="utf-8" ignore-unresolvable="true"></context:property-placeholder>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.pool.maxTotal}"/>
<property name="maxIdle" value="${redis.pool.maxIdle}"/>
<property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}"/>
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>
</bean>
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg ref="jedisPoolConfig"/>
<constructor-arg value="${jedis.host}" type="java.lang.String"/>
<constructor-arg type="int" value="${jedis.port}"/>
</bean>
properties 配置
redis.pool.maxTotal=1000
redis.pool.maxIdle=200
redis.pool.maxWaitMillis=2000
redis.pool.testOnBorrow=true
jedis.host=127.0.0.1
jedis.port=6379
用到的jar包
<!-- redis -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>