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 前言 ...
随机推荐
- TCP的可靠传输(依赖流量控制、拥塞控制、连续ARQ)
TCP可靠性表现在它向应用层提供的数据是无差错,有序,无丢失,即递交的和发送的数据是一样的. 可靠性依赖于流量控制.拥塞控制.连续ARQ等技术 <TCP/IP详解>中的“分组”是不是就是报 ...
- Ubuntu PostgreSql主从切换
主机:192.168.100.70 从机:192.168.100.71 通用配置(即主从都要配置) 修改/etc/postgresql/10/main/pg_hba.conf host all all ...
- Floodlight 中创建消息对象的方法
在 floodlight 中创建各种openflow message 和 action 等採用的是简单工厂方式.BasicFactory类(实现OFMessageFactory接口.) ...
- extjs grid 复制问题还有一种解决方式.
之前的项目中尽管也常常使用到extjs,但也许是没有注意到,也也许是根本就没有须要用到这个功能. 前几天在和客户讨论需求时,客户说想要可以将gird表中的数据复制出来,当时没多想,感觉这功能extjs ...
- YII 数据库查询
$userModel = User::Model(); $userModel->count(); $userModel->count($condition); $userModel-> ...
- 显示解析svg
g公司代码显示svg: SVGParserRenderer drawable = new SVGParserRenderer(context, String svgContent); String s ...
- nyoj--1237--最大岛屿(dfs+数据处理)
最大岛屿 时间限制:1000 ms | 内存限制:65535 KB 难度: 描述 神秘的海洋,惊险的探险之路,打捞海底宝藏,激烈的海战,海盗劫富等等.加勒比海盗,你知道吧?杰克船长驾驶着自己的的战 ...
- vc应用CPictureEx类(重载CStatic类)加载gif动画
1.PictureEx.h文件: //////////////////////////////////////////////////////////////////////// PictureEx. ...
- 你不知道的JavaScript(二)数组
作为一种线性数据结构,几乎每一种编程语言都支持数组类型.和c++.java这些强类型的语言相比,JavaScript数组有些不同,它可以存放任意类型的值.上节中有提到过JS中任意类型的值都可以赋值给任 ...
- 【算法】Floyd-Warshall算法(任意两点间的最短路问题)(判断负圈)
求解所有两点间的最短路问题叫做任意两点间的最短路问题. 可以用动态规划来解决, d[k][i][j] 表示只用前k个顶点和顶点i到顶点j的最短路径长度. 分两种情况讨论: 1.经过顶点k, d[k] ...