spring data redis jackson 配置,工具类
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 配置,工具类的更多相关文章
- 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 ...
- spring data redis的配置类RedisConfig
package com.tz.config; import org.springframework.context.annotation.Bean; import org.springframewor ...
- Spring Data Redis 让 NoSQL 快如闪电(2)
[编者按]本文作者为 Xinyu Liu,文章的第一部分重点概述了 Redis 方方面面的特性.在第二部分,将介绍详细的用例.文章系国内 ITOM 管理平台 OneAPM 编译呈现. 把 Redis ...
- Spring Data Redis 让 NoSQL 快如闪电 (1)
[编者按]本文作者为 Xinyu Liu,详细介绍了 Redis 的特性,并辅之以丰富的用例.在本文的第一部分,将重点概述 Redis 的方方面面.文章系国内 ITOM 管理平台 OneAPM 编译呈 ...
- Spring Data Redis 2.x 中 RedisConfiguration 类的新编写方法
在 Spring Data Redis 1.x 的时候,我们可能会在项目中编写这样一个RedisConfig类: @Configuration @EnableCaching public class ...
- spring mvc Spring Data Redis RedisTemplate [转]
http://maven.springframework.org/release/org/springframework/data/spring-data-redis/(spring-data包下载) ...
- Spring Data Redis入门示例:数据序列化 (四)
概述 RedisTemplate默认使用的是基于JDK的序列化器,所以存储在Redis的数据如果不经过相应的反序列化,看到的结果是这个样子的: 可以看到,出现了乱码,在程序层面上,不会影响程序的运行, ...
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
一.概念简介: Redis: Redis是一款开源的Key-Value数据库,运行在内存中,由ANSI C编写,详细的信息在Redis官网上面有,因为我自己通过google等各种渠道去学习Redis, ...
- Spring Data Redis学习
本文是从为知笔记上复制过来的,懒得调整格式了,为知笔记版本是带格式的,内容也比这里全.点这里 为知笔记版本 Spring Data Redis 学习 Version 1.8.4.Release 前言 ...
随机推荐
- Vue-router入门
1.npm install vue-router --save-dev 安装路由包,在安装脚手架时实际上可以直接安装 2.解读核心文件 router/index.js文件 import Vue fro ...
- HDU 3073 Saving Beans
Saving Beans Time Limit: 3000ms Memory Limit: 32768KB This problem will be judged on HDU. Original I ...
- PatentTips - Increasing turbo mode residency of a processor
BACKGROUND Many modern operating systems (OS's) use the Advanced Configuration and Power Interface ( ...
- 百度语音识别服务 —— 语音识别 REST API 开发笔记
http://blog.csdn.net/lw_power/article/details/51771267
- redis五种数据结构的指令
一.基本常用命令 select 选择数据库 0-15共16个库 keys 返回所有的键 keys mylist*代表取出所有mylist开头的键 exists 确认一个键存在不 del 删除 ...
- WPF silverlight获取子控件(获取DataTemplate里的子控件)
public static class VisualTreeExtensions { /// <summary> /// 获取父节点控件 /// </summary> /// ...
- 如何获取Assets的路径
有两种方法可以获取assets的绝对路径: 第一种方法: String path = file:///android_asset/文件名; 第二种方法: InputStream abpath = ge ...
- CoreData 从入门到精通(三)关联表的创建
上篇博客中讲了 CoreData 里增删改查的使用,学到这里已经可以应对简单的数据存储需求了.但是当数据模型复杂起来时,例如你的模型类中除了要存储 CoreData 里支持的数据类型外,还有一些自定义 ...
- 文档相关命令-cat命令查看一个文件
用于查看一个文件的内容并将其显示在屏幕上 cat 后直接加上文件名 -n 表示显示行号 cat -n dirb/filee -A 显示所有内容包括特殊字符 cat -A dirb/filee
- bower 代理
bower 设置: 修改 .bowerrc 文件(如无则新增): { "proxy": "http://proxy.mysite.com:8080", &quo ...