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 前言 ...
随机推荐
- js实现新闻滚动实例
<html> <head> <meta http-equiv="Content-Type" content="text/html; char ...
- HDU 2512
水题 #include <iostream> #include <cstdio> #include <algorithm> #define LL __int64 # ...
- Oracle 实现 mysql 更新 update limit
oracle给人的感觉非常落后.使用非常不方便,Toad 这个软件又笨又迟钝.pl/sql更是,90年代的界面风格,速度还卡得要死.并且oracle不支持limit .by default7#zbph ...
- python 提取主域名和子域名代码——先根据规则提取,如果有问题,则使用tldextract
import tldextract def extract_domain(domain): suffix = {'.com','.la','.io', '.co', '.cn','.info', '. ...
- angular与angularjs常用指令的不同写法整理
angularjs与angular 常用的指令写法的区别; 一:angularjs指令 1.ng-bind 使用给定的变量或表达式的值来替换 HTML 元素的内容 <p ng-bind=&quo ...
- 最长回文子串 C++实现 java实现 leetcode系列(五)
给定一个字符串 s,找到 s 中最长的回文子串.你可以假设 s 的最大长度为 1000. 示例 1: 输入: "babad" 输出: "bab" 注意: &qu ...
- sas与mysql连接方法
2012年8月11日 sas 9.1.3 版本 与mysql 连接 测试,可以与数据库连接1 通过odbc 直接连通 pass through connect to odbc create tabl ...
- 【DNN 系列 创建WEB模块 项目】
现在DNN已经更新到8.0.3 然而使用7.0 的项目模块 会报错, 就是填写网站的时候 会再网站的项目当中添加文件夹这样会破坏网站 所以来自己创建自己的模板项目 首选创建空的WEB 项目网站 创建完 ...
- javascript对象的相关操作
Window对象 我们知道浏览器对象模型(BOM)是javascript的组成之一,它提供了独立于内容与浏览器窗口进行交互的对象.其分层结构如下: window对象是整个BOM的核心其有documen ...
- C# 热敏打印机 小票打印机 打印图片
最近一直在研究并口小票打印机打印图片问题,这也是第一次和硬件打交道,不过还好,最终成功了. 这是DEMO的窗体: 下面是打印所需要调用的代码: 因为我们这里主要是打印条形码和二维码,所以以条形码和二维 ...