Redis配置

#Redis
spring.redis.host=
spring.redis.port=6379
spring.redis.database=0
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=1500
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=30000

RedisConfig.java Redis配置文件


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component; import java.lang.reflect.Method; @Configuration
@Component
public class RedisConfig extends CachingConfigurerSupport { private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class); public RedisConfig(){
logger.info("init RedisConfig...");
} /**
* 生成key的策略
*
* @return
*/
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
} /**
* 管理缓存
*
* @param redisTemplate
* @return
*/
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
// rcm.setDefaultExpiration(60);//秒
return rcm;
} /**
* RedisTemplate配置
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);//如果key是String 需要配置一下StringSerializer,不然key会乱码 /XX/XX
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
} }

RedisUtils.java Redis工具类

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component; import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit; /**
* redicache 工具类
*
*/
@SuppressWarnings("unchecked")
@Component
public class RedisUtils { private static final Logger log = LoggerFactory.getLogger(RedisUtils.class); private static final PropertiesUtils redisProper = new PropertiesUtils("spring/redis-time-config.properties"); @SuppressWarnings("rawtypes")
@Autowired
private RedisTemplate redisTemplate; /**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
} public int getCountPattern(String pattern){
Set<Serializable> keys = redisTemplate.keys(pattern);
return keys==null?0:keys.size();
}
/**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
} /**
* 批量删除key
*
* @param keys
*/
public void removeKeys(final Set<String> keys) {
if (keys.size() > 0)
redisTemplate.delete(keys);
} public Long ttl(String key) {
return StringUtils.isNoneEmpty(key) ? Long.valueOf(-1L) : redisTemplate.getExpire(key);
} /**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
} /**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
} /**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
} /**
* 读取缓存
*
* @param key
* @return
*/
public Long size(final String key) {
Long result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.size(key);
return result;
} public <K> Set<K> keys(K pattern){
return redisTemplate.keys(pattern);
} /**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
return set(key, value, expireTime, TimeUnit.SECONDS);
} /**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, timeUnit);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean setInt(final String key, int value, Long expireTime, TimeUnit timeUnit) {
boolean result = false;
try {
ValueOperations<String, Integer> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, timeUnit);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean setInt(final String key, int value) {
boolean result = false;
try {
ValueOperations<String, Integer> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 写入缓存
*
* @param key
* @param key
* @return
*/
public int getInt(final String key) {
int result = -1;
if (exists(key)) {
ValueOperations<String, Integer> operations = redisTemplate.opsForValue();
result = operations.get(key);
}
return result;
} public Long increment(String key, long val){
if( exists(key) ){
return redisTemplate.opsForValue().increment(key, val);
}
return null;
} public Long addHyperLogLog(Object val1, Object ...val2){
return redisTemplate.opsForHyperLogLog().add(val1, val2);
} public Long sAdd(Object key, Object... values) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForSet().add(key, values);
} public Set<String> sMembers(String key) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForSet().members(key);
} public Long sRem(Object key, Object... values) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForSet().remove(key, values);
} public Object sPop(Object key) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForSet().pop(key);
} public boolean sMove(Object srcKey, Object destKey, Object member) {
return (!isNullOrEmpty(srcKey) && !isNullOrEmpty(destKey)) && ((member != null) && redisTemplate.opsForSet().move(srcKey, member, destKey));
} public Long sLen(Object key) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForSet().size(key);
} public boolean sIsMember(Object key, Object member) {
return !isNullOrEmpty(key) && redisTemplate.opsForSet().isMember(key, member);
} public Set<Object> sInter(Object key, Object... keys) {
return key == null ? null : redisTemplate.opsForSet().intersect(key, keys);
} public Long sInterStore(Object destKey, Object srckey, Object... srcKeys) {
return !isNullOrEmpty(destKey) && srckey != null ? redisTemplate.opsForSet().intersectAndStore(srckey, srcKeys, destKey) : null;
} public Set<Object> sUnion(Object... keys) {
if (keys != null && keys.length != 0) {
List keyList = Arrays.asList(keys);
return redisTemplate.opsForSet().union(keyList.remove(0), keyList);
} else {
return null;
}
} public Long sUnionStore(Object dstKey, Object... keys) {
if (keys != null && keys.length != 0 && dstKey != null) {
List keyList = Arrays.asList(keys);
return redisTemplate.opsForSet().unionAndStore(keyList.remove(0), keyList, dstKey);
} else {
return null;
}
} public Set<Object> sDiff(Object... keys) {
if (keys != null && keys.length != 0) {
List keyList = Arrays.asList(keys);
return redisTemplate.opsForSet().difference(keyList.remove(0), keyList);
} else {
return null;
}
} public Long sDiffStore(Object dstKey, Object... keys) {
if (!isNullOrEmpty(dstKey) && keys != null && keys.length != 0) {
List keyList = Arrays.asList(keys);
return redisTemplate.opsForSet().differenceAndStore(keyList.remove(0), keyList, dstKey);
} else {
return null;
}
} public boolean hSet(String key, Map<String, Object> param, Long expireTime, TimeUnit timeUnit) {
try {
hSet(key, param);
redisTemplate.expire(key, expireTime, timeUnit);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
} public void hSet(String key, Map<String, Object> param) {
HashOperations<String, String, Object> hashOperations = redisTemplate.opsForHash();
Set<Map.Entry<String, Object>> entrySet = param.entrySet();
for (Map.Entry<String, Object> entry : entrySet) {
hashOperations.put(key, entry.getKey(), entry.getValue());
}
} public void hSet(String key, Object field, Object value) {
redisTemplate.opsForHash().put(key, field, value);
} public Object hGet(String key, Object field) {
if (StringUtils.isEmpty(key)) {
return null;
}
return redisTemplate.opsForHash().get(key, field);
} public String hGet(String key, String field) {
if (StringUtils.isEmpty(key)) {
return null;
}
HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
return hashOperations.get(key, field);
} public boolean hExists(String key, Object hashKey) {
return !isNullOrEmpty(key) && redisTemplate.opsForHash().hasKey(key, hashKey);
} public Long hDel(Object key, Object... hashKeys) {
return isNullOrEmpty(key) ? Long.valueOf(0L) : redisTemplate.opsForHash().delete(key, hashKeys);
} public Long hLen(String key) {
return StringUtils.isNoneEmpty(key) ? Long.valueOf(0L) : redisTemplate.opsForHash().size(key);
} public Set<Object> hKeys(Object key) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForHash().keys(key);
} public List<Object> hValues(Object key) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForHash().values(key);
} public Map<Object, Object> hGetAll(Object key) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForHash().entries(key);
} public Object getUnknownType(Object key){
try {
DataType dataType = redisTemplate.type(key);
switch (dataType){
case NONE:
log.info("key:[{}]不存在", key);
return null;
case STRING:
return redisTemplate.opsForValue().get(key);
case LIST:
return redisTemplate.opsForList().range(key, 0, -1);
case SET:
return redisTemplate.opsForSet().members(key);
case ZSET:
return redisTemplate.opsForZSet().range(key, 0, -1);
case HASH:
return redisTemplate.opsForHash().entries(key);
default:
return null;
}
}catch (Exception e){
log.error("查询出现异常:{}", e);
return null;
}
} private static boolean isNullOrEmpty(Object obj) {
boolean result = false;
if (obj == null || "null".equals(obj) || "".equals(obj.toString().trim())) {
result = true;
}
return result;
} public void setRedisValue(String key, Object value,String redisKey){
//添加缓存
String[] redispropers=redisProper.getPropertiesValues(redisKey);
Long redisExp=Long.valueOf(redispropers[0]);
TimeUnit redisTimeType= UtilHelper.getTimeUtil(redispropers[1]);
redisTemplate.opsForValue().set(key,value,redisExp, redisTimeType);
} }

SpringBoot Redis序列化配置的更多相关文章

  1. Springboot+Redis序列化坑

    今天在测试springboot整合redis的时候遇到下面这个坑,百度来百度去发现提示都是ajax的问题,真的是醉了,错误提示如下所示,不信大家可以直接复制百度一下答案是什么(流泪中....),错误如 ...

  2. Spring Boot 结合 Redis 序列化配置的一些问题

    前言 最近在学习Spring Boot结合Redis时看了一些网上的教程,发现这些教程要么比较老,要么不知道从哪抄得,运行起来有问题.这里分享一下我最新学到的写法 默认情况下,Spring 为我们提供 ...

  3. springboot +redis配置

    springboot +redis配置 pom依赖 <dependency> <groupId>org.springframework.boot</groupId> ...

  4. SpringBoot + Redis:基本配置及使用

    注:本篇博客SpringBoot版本为2.1.5.RELEASE,SpringBoot1.0版本有些配置不适用 一.SpringBoot 配置Redis 1.1 pom 引入spring-boot-s ...

  5. Spring-Boot项目中配置redis注解缓存

    Spring-Boot项目中配置redis注解缓存 在pom中添加redis缓存支持依赖 <dependency> <groupId>org.springframework.b ...

  6. (二)Redis在Mac下的安装与SpringBoot中的配置

    1 下载Redis 官网下载,下载 stable 版本,稳定版本. 2 本地安装 解压:tar zxvf redis-6.0.1.tar.gz 移动到: sudo mv redis-6.0.1 /us ...

  7. SpringBoot Redis使用fastjson进行序列化

    在使用spring-data-redis,默认情况下是使用org.springframework.data.redis.serializer.JdkSerializationRedisSerializ ...

  8. 补习系列(14)-springboot redis 整合-数据读写

    目录 一.简介 二.SpringBoot Redis 读写 A. 引入 spring-data-redis B. 序列化 C. 读写样例 三.方法级缓存 四.连接池 小结 一.简介 在 补习系列(A3 ...

  9. 补习系列(13)-springboot redis 与发布订阅

    目录 一.订阅发布 常见应用 二.Redis 与订阅发布 三.SpringBoot 与订阅发布 A. 消息模型 B. 序列化 C. 发布消息 D. 接收消息 小结 一.订阅发布 订阅发布是一种常见的设 ...

随机推荐

  1. c# 解决读取Excel混合文本类型,数据读取失败的解决方法

    错误重现: ----------------------------------------------------------------------- 在导入Excel读取数据时,其中的一个字段保 ...

  2. &、|、~与&&、||、! 谬误

    按位运算符(&.|.~)的操作是被默认为一个二进制的位序列,分别对其中的每个位进行操作. 逻辑运算符(&&.||.!)将操作数当成非真及假,非假及真.通常就是将0当成假,非0即 ...

  3. strak组件(3):URL别名的优化

    将生成URL别名的功能进行解耦.效果和上一节的一样. 效果图: 新增函数 get_url_name(self, param) # 生成url别名,需要一个参数(list/add/edit/delete ...

  4. 单源次短路径:poj:3255-Roadblocks

    Roadblocks Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 17521 Accepted: 6167 Descripti ...

  5. io编程,python

    IO在计算机中指Input/Output,也就是输入和输出. Stream(流): 可以把流想象成一个水管,数据就是水管里的水,但是只能单向流动.Input Stream就是数据从外面(磁盘.网络)流 ...

  6. jdk1.8源码学习笔记

    前言: 前一段时间开始学习了一些基本的数据结构和算法,算是弥补了这方面的知识短板,但是仅仅是对一些算法的了解,目前工作当中也并没有应用到这些,因此希望通过结合实际例子来学习,巩固之前学到的内容,思前想 ...

  7. js调用js的方法

    a.js文件调用b.js文件时,需要在a.js的第一行添加代码 document.write(" <script language=\"javascript\" s ...

  8. laravel5.5任务调度

    目录 1. 定义调度 1.1 使用Closure 1.2 Artisan 命令调度 1.3 队列任务调度 1.4 Shell 命令调度 1.5 调度频率设置 1.6 闭包测试限制 1.7 避免任务重复 ...

  9. CSS 一些基础知识(优先级、行内元素的一些属性、font-size单位) 怎样不加载图片

    CSS大小写不敏感 选择器优先级如下所示: 在属性后面使用 !important 会覆盖页面内任何位置定义的元素样式. 作为style属性写在元素内的样式 id选择器 类选择器 标签选择器 通配符选择 ...

  10. 【APUE】Chapter11 Threads

    看完了APUE第三版的Chapter11 Threads,跟着书上的demo走了一遍,并且参考了这个blog(http://www.cnblogs.com/chuyuhuashi/p/4447817. ...