spring data redis 序列化有jdk 、jackson、string 等几种类型,自带的jackson不熟悉怎么使用,于是用string类型序列化,把对象先用工具类转成string,代码如下:

application.xml中配置

<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
<property name="hostName" value="${redis.hostName}"></property>
<property name="port" value="${redis.port}"></property>
<property name="password" value="${redis.password}"></property>
<property name="timeout" value="${redis.timeout}" />
<property name="usePool" value="true" />
<property name="poolConfig" ref="jedisPoolConfig" />
</bean> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.maxTotal}"></property>
<property name="maxIdle" value="${redis.maxIdle}"></property>
<property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property>
<property name="testOnBorrow" value="${redis.testOnBorrow}"></property>
</bean> <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" /> <!-- <bean id="jacksonJsonRedisSerializer" class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer" >
<constructor-arg type="java.lang.Class" value="java.lang.Object"/>
</bean> --> <bean id="jacksonJsonRedisSerializer" class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer" >
<constructor-arg type="java.lang.Class" value="java.lang.Object"/>
</bean> <bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"></property>
<property name="keySerializer" ref="stringRedisSerializer"/>
<property name="valueSerializer" ref="stringRedisSerializer" />
<property name="hashKeySerializer" ref="stringRedisSerializer" />
<property name="hashValueSerializer" ref="stringRedisSerializer"/>
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:redis.properties</value>
</list>
</property>
</bean> redis.properties #redis连接池配置
redis.maxTotal=300
redis.maxIdle=20
#读取超时
redis.maxWaitMillis=5000
redis.testOnBorrow=true #redis连接配置
redis.hostName=192.168.100.75
redis.port=6379
redis.password=desc@1997
#连接超时
redis.timeout=5000

RedisBaseDao

@Component
public class RedisBaseDao {
/**
* 日志记录
*/
private static Logger logger = Logger.getLogger(RedisBaseDao.class);
@Autowired
protected RedisTemplate<String, String> redisTemplate; public RedisTemplate<String, String> getRedisTemplate() {
return redisTemplate;
}
/**
* 缓存value操作
* @param k
* @param v
* @param time
* @return
*/
public boolean cache(String k, Object v, long time) {
String key = k;
try {
long s=System.currentTimeMillis();
ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
valueOps.set(key, Json2Util.obj2String(v));
if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
long e=System.currentTimeMillis();
if(e-s>2000){
logger.error("key:"+key+" redis time use"+(e-s));
} else if(logger.isDebugEnabled()){
logger.debug("key:"+key+" redis time use"+(e-s));
}
return true;
} catch (Throwable t) {
logger.error("缓存[" + key + "]失败, value[" + v + "]", t);
}
return false;
}
/**
* 添加list
* @Autor : xiongjinpeng jpx_011@163.com
* @Date : 2017年7月7日 下午2:37:31
* @param k
* @param v
* @param time
* @return
*/
// public boolean cacheList(String k, Collection v, long time) {
// String key = k;
// try {
// long s=System.currentTimeMillis();
// redisTemplate.delete(key);
// ListOperations<String, Object> list=redisTemplate.opsForList();
// list.leftPushAll(key, v);
// if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
// long e=System.currentTimeMillis();
// if(e-s>2000){
// logger.error("redis time use "+(e-s));
// }
// return true;
// } catch (Throwable t) {
// logger.error("缓存[" + key + "]失败, value[" + v + "]", t);
// }
// return false;
// }
// public boolean cacheList(String k, Collection v) {
// return cacheList(k, v, -1);
// }
// public <T> List<T> getList(String k,int start,int end) {
// try {
// long s=System.currentTimeMillis();
// ListOperations<String, Object> valueOps=redisTemplate.opsForList();
// List<T> o=(List<T>) valueOps.range(k, start, end);
// long e=System.currentTimeMillis();
// if(e-s>2000){
// logger.error("redis time use "+(e-s));
// }
// return o;
// } catch (Throwable t) {
// logger.error("获取缓存失败key[" + k + ", error[" + t + "]");
// }
// return null;
// }
// public <T> List<T> getList(String k){
// return getList(k, 0, -1);
// }
/**
* 缓存value操作
* @param k
* @param v
* @return
*/
public boolean cache(String k, Object v) {
return cache(k, v, RedisUtil.keytimeout);
} public boolean containsKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Throwable t) {
logger.error("判断缓存存在失败key[" + key + ", error[" + t + "]");
}
return false;
} /**
* 获取缓存
* @param k
* @return
*/
// public Object get(String k) {
// return get(k,RedisUtil.keytimeout);
// }
//
// public Object get(String k,long time) {
// try {
// long s=System.currentTimeMillis();
// ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
// Object o=valueOps.get(k);
// if (time > 0) redisTemplate.expire(k, time, TimeUnit.SECONDS);
// long e=System.currentTimeMillis();
// if(e-s>2000){
// logger.error("key:"+k+" redis time use "+(e-s));
// } else if(logger.isDebugEnabled()){
// logger.debug("key:"+k+" redis time use"+(e-s));
// }
// return o;
// } catch (Throwable t) {
// logger.error("获取缓存失败key[" + k + ", error[" + t + "]");
// }
// return null;
// } public <T> T get(String k,Class<T> clazz) {
return get(k,RedisUtil.keytimeout, clazz);
}
public <T> T get(String k,long time,Class<T> clazz) {
try {
long s=System.currentTimeMillis();
ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
String o=valueOps.get(k);
if (time > 0) redisTemplate.expire(k, time, TimeUnit.SECONDS);
long e=System.currentTimeMillis();
if(e-s>2000){
logger.error("key:"+k+" redis time use "+(e-s));
} else if(logger.isDebugEnabled()){
logger.debug("key:"+k+" redis time use"+(e-s));
}
if(o!=null){
return Json2Util.getObjectMapper().readValue(o, clazz);
}
} catch (Throwable t) {
logger.error("获取缓存失败key[" + k + ", error[" + t + "]");
}
return null;
}
public <T> List<T> getList(String k,long time,Class<T> clazz) {
try {
long s=System.currentTimeMillis();
ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
String o=valueOps.get(k);
if (time > 0) redisTemplate.expire(k, time, TimeUnit.SECONDS);
long e=System.currentTimeMillis();
if(e-s>2000){
logger.error("key:"+k+" redis time use "+(e-s));
} else if(logger.isDebugEnabled()){
logger.debug("key:"+k+" redis time use"+(e-s));
}
if(o!=null){
JavaType javaType = Json2Util.getObjectMapper().getTypeFactory().constructParametricType(List.class, clazz);
List<T> list = Json2Util.getObjectMapper().readValue(o, javaType);
return list;
}
} catch (Throwable t) {
logger.error("获取缓存失败key[" + k + ", error[" + t + "]");
}
return null;
}
public <T> List<T> getList(String k,Class<T> clazz) {
return getList(k, RedisUtil.keytimeout, clazz);
}
/**
* 移除缓存
* @param key
* @return
*/
public boolean remove(String key) {
try {
redisTemplate.delete(key);
return true;
} catch (Throwable t) {
logger.error("获取缓存失败key[" + key + ", error[" + t + "]");
}
return false;
}
/**
* 模糊匹配,不建议使用,影响性能,只在一些数据重置的时候使用
* @Date : 2017年7月6日 下午4:13:45
* @param pattern
* @return
*/
@Deprecated
public Set<String> keys(String pattern) {
try {
long s=System.currentTimeMillis();
Set<String> keys=redisTemplate.keys(pattern);
long e=System.currentTimeMillis();
if(e-s>2000){
logger.error("redis time use "+(e-s));
}
return keys;
} catch (Throwable t) {
logger.error("获取缓存失败pattern[" + pattern + ", error[" + t + "]");
}
return null;
} public String flushDB() {
return redisTemplate.execute(new RedisCallback<String>() {
public String doInRedis(RedisConnection connection) throws DataAccessException {
connection.flushDb();
return "ok";
}
});
} public long dbSize() {
return redisTemplate.execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
return connection.dbSize();
}
});
}
}

RedisUtil

public class RedisUtil {
//单例
private RedisUtil(){}
private static RedisBaseDao dao=null;
static {
if(dao==null){
synchronized (RedisUtil.class) {
if(dao==null){
dao=ContextUtil.getBean(RedisBaseDao.class);
try {
String keytimeoutstr=ContextUtil.getInitConfig("redis.keytimeout");
String unit=keytimeoutstr.substring(keytimeoutstr.length()-1);
Integer num=Integer.parseInt(keytimeoutstr.substring(0,keytimeoutstr.length()-1));
if(unit.equals("d")){
keytimeout=num*24*60*60;
} else if(unit.equals("h")){
keytimeout=num*60*60;
} else if(unit.equals("m")){
keytimeout=num*60;
} else if(unit.equals("s")){
keytimeout=num;
} else {
throw new RuntimeException("redis key timeout初始化失败");
}
} catch (Exception e) {
throw new RuntimeException("redis key timeout初始化失败");
}
}
}
}
}
public static RedisBaseDao getRedisDao() {
return dao;
} public static long keytimeout=30*24*60*60;//秒 }

使用类,

CommonCache

public class CommonCache {

    /**
* 查询缓存 * @Date : 2017年7月5日 下午3:15:47
* @param userId
* @return
*/
public static FileCache queryFileCache(Long fid){
if(fid==null){
return null;
}
String key=CachePrefix.filecache_prefix+fid;
FileCache u=RedisUtil.getRedisDao().get(key,FileCache.class);
if(u==null){
return refreshFileCache(fid);
} else {
return u;
}
}
/**
* 刷新缓存 * @Date : 2017年7月5日 下午3:15:39
* @param userId
*/
public static FileCache refreshFileCache(Long fid){
if(fid==null){
return null;
}
IBaseDao dao=ContextUtil.getBean(IBaseDao.class);
String key=CachePrefix.filecache_prefix+fid;
StringBuffer sql = new StringBuffer();
sql.append("select f.f_isdeleted,f.f_id,f.f_name,f.f_extension,f.f_type,f.f_size,f.f_create_time,f.f_oss_bucket from t_file f where f.f_id=?");
FileCache userExt = dao.queryObjectBySql(FileCache.class, sql.toString(), new Object[]{fid});
RedisUtil.getRedisDao().cache(key, userExt);
return userExt;
} }

json使用jackson个人感觉是最快的

Json2Util

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; /**
* @Description :
* @Autor : xiongjinpeng jpx_011@163.com
* @Date : 2016年1月26日 上午10:11:41
* @version :
*/
public class Json2Util { private static ObjectMapper objectMapper=null;
static {
if(objectMapper==null){
synchronized (Json2Util.class) {
if(objectMapper==null){
objectMapper=new ObjectMapper();
objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
}
}
}
public static ObjectMapper getObjectMapper() {
return objectMapper;
}
public static String obj2String(Object obj){
String s = "";
try {
s = getObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
private Json2Util(){} public static void main(String[] args) throws Exception{
}
}

spring data redis jackson 配置,工具类的更多相关文章

  1. spring data jpa和spring data redis同时配置时,出现Multiple Spring Data modules found, entering strict repository configuration mode错误

    问题说明 data jpa和data redis同时配置时,出现Spring modules spring Spring Data Release Train <dependencyManage ...

  2. spring data redis的配置类RedisConfig

    package com.tz.config; import org.springframework.context.annotation.Bean; import org.springframewor ...

  3. Spring Data Redis 让 NoSQL 快如闪电(2)

    [编者按]本文作者为 Xinyu Liu,文章的第一部分重点概述了 Redis 方方面面的特性.在第二部分,将介绍详细的用例.文章系国内 ITOM 管理平台 OneAPM 编译呈现. 把 Redis ...

  4. Spring Data Redis 让 NoSQL 快如闪电 (1)

    [编者按]本文作者为 Xinyu Liu,详细介绍了 Redis 的特性,并辅之以丰富的用例.在本文的第一部分,将重点概述 Redis 的方方面面.文章系国内 ITOM 管理平台 OneAPM 编译呈 ...

  5. Spring Data Redis 2.x 中 RedisConfiguration 类的新编写方法

    在 Spring Data Redis 1.x 的时候,我们可能会在项目中编写这样一个RedisConfig类: @Configuration @EnableCaching public class ...

  6. spring mvc Spring Data Redis RedisTemplate [转]

    http://maven.springframework.org/release/org/springframework/data/spring-data-redis/(spring-data包下载) ...

  7. Spring Data Redis入门示例:数据序列化 (四)

    概述 RedisTemplate默认使用的是基于JDK的序列化器,所以存储在Redis的数据如果不经过相应的反序列化,看到的结果是这个样子的: 可以看到,出现了乱码,在程序层面上,不会影响程序的运行, ...

  8. Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解

    一.概念简介: Redis: Redis是一款开源的Key-Value数据库,运行在内存中,由ANSI C编写,详细的信息在Redis官网上面有,因为我自己通过google等各种渠道去学习Redis, ...

  9. Spring Data Redis学习

    本文是从为知笔记上复制过来的,懒得调整格式了,为知笔记版本是带格式的,内容也比这里全.点这里 为知笔记版本 Spring Data Redis 学习 Version 1.8.4.Release 前言 ...

随机推荐

  1. 实现双向数据绑定mvvm

    实现双向数据绑定mvvm  

  2. Java分布式爬虫Nutch教程——导入Nutch工程,执行完整爬取

    Java分布式爬虫Nutch教程--导入Nutch工程,执行完整爬取 by briefcopy · Published 2016年4月25日 · Updated 2016年12月11日 在使用本教程之 ...

  3. 练练脑,继续过Hard题目

    http://www.cnblogs.com/charlesblc/p/6384132.html 继续过Hard模式的题目吧.   # Title Editorial Acceptance Diffi ...

  4. java mail邮件发送(带附件) 支持SSL

    java mail邮件发送(带附件)有三个类 MailSenderInfo.java package mail; import java.util.Properties; import java.ut ...

  5. linux高级技巧:heartbeat+lvs(三)

    之前我们把LVS和heartbeat都单独进行了測试,是时候进行合并了 1.LVS+heartbeat:         首先显示我们的控制台:                        让这两个 ...

  6. 继承QWidget的派生类控件不能设置QSS问题解决(使用style()->drawPrimitive(QStyle::PE_Widget,也就是画一个最简单最原始的QWidget,不要牵扯其它这么多东西)

    自定义控件时基类用了QWidget,发现qss设置不起作用,需要重载其paintEvent函数即可: 如下代码: void CCustomWidget::paintEvent(QPaintEvent* ...

  7. Vuejs2.0学习之二(Render函数,createElement,vm.$slots,函数化组件,模板编译,JSX)

    时隔一周多,因为一些别的事情绊住了,下面接着写.中间这段时间也有看官方文档,发现正如他所说90%的基础内容都一样,所以这里直接跳到我比较关注的东东上,要是想看看哪些不一样,可以参考这个http://v ...

  8. NOIP2017提高组模拟赛5 (总结)

    NOIP2017提高组模拟赛5 (总结) 第一题 最远 奶牛们想建立一个新的城市.它们想建立一条长度为N (1 <= N <= 1,000,000)的 主线大街,然后建立K条 (2 < ...

  9. bzoj2150: 部落战争(匈牙利)

    2150: 部落战争 题目:传送门 题解: 辣鸡数据..毁我AC率 先说做法,很容易就可以看出是二分图匹配的最小路径覆盖(可能是之前不久刚做过类似的题) 一开始还傻逼逼的去直接连边然后准备跑floyd ...

  10. 简单的beego分页功能代码

    一个简单的beego分页小插件(源代码在最下面): 支持条件查询 支持参数保留 支持自定义css样式 支持表/视图 支持参数自定义 默认为pno 支持定义生成链接的个数 使用方式: 1)action中 ...