Redis和SpringBoot整合RedisUtils类
一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<!--<version></version>-->
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency> <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
二、在application.yml 配置redis服务器
项目没完成,配置不在子项目中
三、写一个redis配置类
package com.nps.redis.config; /*
* @author XueWeiWei
* @date 2019/8/29 15:38
*/ import com.nps.redis.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig; import java.util.HashSet;
import java.util.Set; @Configuration
@PropertySources({@PropertySource(
value = {"classpath:nps-redis.properties","file:${xww.redis.config.file}"},
encoding = "UTF-8",
ignoreResourceNotFound = true
)})
public class RedisConfig {
//idle 没有工作的
//eviction 驱逐
//cluster 团,簇
@Value("${xww.redis.maxIdle}")
private Integer maxIdle;
@Value("${xww.redis.maxTotal}")
private Integer maxTotal;
@Value("${xww.redis.maxWaiMillis}")
private Integer maxWaitMillis;
@Value("${xww.redis.minEvictableIdleTimeMillis}")
private Integer minEvictableIdleTimeMillis;
@Value("${xww.redis.numTestsPerEvictionRun}")
private Integer numTestsPerEvictionRun;
@Value("${xww.redis.timeBetweenEvictionRunsMillis}")
private long timeBetweenEvictionRunsMillis;
@Value("${xww.redis.testOnBorrow}")
private boolean testOnBorrow;
@Value("${xww.redis.testWhileIdle}")
private boolean testWhileIdle;
@Value("${xww.redis.clusterNodes}")
private String clusterNodes;
@Value("${xww.redis.clusterMaxRedirects}")
private Integer mmaxRedirectsac; public RedisConfig() {
} @Bean
public JedisPoolConfig jedisPoolConfig(){
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(this.maxIdle);
jedisPoolConfig.setMaxIdle(this.maxTotal);
jedisPoolConfig.setMaxWaitMillis(this.maxWaitMillis);
jedisPoolConfig.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis);
jedisPoolConfig.setNumTestsPerEvictionRun(this.numTestsPerEvictionRun);
jedisPoolConfig.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
jedisPoolConfig.setTestOnBorrow(this.testOnBorrow);
jedisPoolConfig.setTestWhileIdle(this.testWhileIdle);
return jedisPoolConfig;
} @Bean
public RedisClusterConfiguration redisClusterConfiguration(){
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
String[] serverArray = this.clusterNodes.split(",");
Set<RedisNode> nodes = new HashSet<>();
String[] var4 = serverArray;
int var5 = serverArray.length; for (int var6 = 0; var6 < var5; var6++) {
String ipPort = var4[var6];
String[] ipAndPort = ipPort.split(":");
nodes.add(new RedisNode(ipAndPort[0].trim(), Integer.valueOf(ipAndPort[1])));
} redisClusterConfiguration.setClusterNodes(nodes);
redisClusterConfiguration.setMaxRedirects(this.mmaxRedirectsac);
return redisClusterConfiguration;
} @Bean
public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig, RedisClusterConfiguration redisClusterConfiguration){
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration, jedisPoolConfig);
return jedisConnectionFactory;
} @Bean
public RedisTemplate<String, Object> functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
this.iniDomainRedisTemplate(redisTemplate,redisConnectionFactory);
return redisTemplate;
} private void iniDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory redisConnectionFactory){
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setEnableTransactionSupport(false);
redisTemplate.setConnectionFactory(redisConnectionFactory);
} @Bean(name = {"redisUtil"})
public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate){
RedisUtil redisUtil = new RedisUtil();
redisUtil.setRedisTemplate(redisTemplate);
return redisUtil;
} }
四、编写一个RedisUtil类
package com.nps.redis.utils; import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils; import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit; /*
* @author XueWeiWei
* @date 2019/8/30 11:19
*/
public class RedisUtil {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
private RedisTemplate<String, Object> redisTemplate; public RedisUtil() {
} public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
} /**
* 指定缓存失效时间
* @param key
* @param time
* @return
*/
public boolean expire(String key, long time){
try{
if (time > 0L){
this.redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
} } /**
* 根据key获取过期时间
* @param key
* @return
*/
public long getExpire(String key){
return this.redisTemplate.getExpire(key,TimeUnit.SECONDS);
} /**
* 判断缓存中是否含有key
* @param key
* @return
*/
public boolean hasKey(String key){
try{
return this.redisTemplate.hasKey(key);
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
}
} /**
* 批量删除缓存
* @param key
*/
public void del(String...key){
if (key != null && key.length > 0){
if (key.length == 1){
this.redisTemplate.delete(key[0]);
}else {
this.redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
} /**
* 根据key获取缓存
* @param key
* @return
*/
public Object get(String key){
return key == null ? null : this.redisTemplate.opsForValue().get(key);
} /**
* 普通存入缓存数据
* @param key
* @param value
* @return
*/
public boolean set(String key, Object value){
try{
this.redisTemplate.opsForValue().set(key, value);
return true;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
}
} /**
* 普通存入缓存,并设置时间
* @param key
* @param value
* @param time
* @return
*/
public boolean set(String key, Object value, long time){
try{
if (time > 0L)
this.redisTemplate.opsForValue().set(key,value, time, TimeUnit.SECONDS);
else
this.set(key,value);
return true;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
}
} /**
* 递增
* @param key
* @param delta
* @return
*/
public long incr(String key, long delta){
if (delta < 0L){
throw new RuntimeException("递增因子必须大于0");
}else
return this.redisTemplate.opsForValue().increment(key, delta);
} /**
* 递减
* @param key
* @param delta
* @return
*/
public long decr(String key, long delta){
if (delta < 0L){
throw new RuntimeException("递增因子必须大于0");
}else
return this.redisTemplate.opsForValue().increment(key, -delta);
} /**
* hashget
* @param key
* @param item
* @return
*/
public Object hget(String key, String item){
return this.redisTemplate.opsForHash().get(key, item);
} /**
* 获取hashkey对应的所有键值
* @param key
* @return
*/
public Map<Object, Object> hmget(String key){
return this.redisTemplate.opsForHash().entries(key);
} /**
* hashset
* @param key
* @param map
* @return
*/
public boolean hmset(String key, Map<String, Object> map){
try {
this.redisTemplate.opsForHash().putAll(key, map);
return true;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
}
} /**
* hashset 并设置时间
* @param key
* @param map
* @param time
* @return
*/
public boolean hmset(String key, Map<String, Object> map, long time){
try {
this.redisTemplate.opsForHash().putAll(key, map);
if (time > 0L){
this.expire(key, time);
}
return true;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
}
} /**
* 向一张表中放入数据,如果不存在就创建
* @param key
* @param item
* @param value
* @return
*/
public boolean hset(String key, String item, Object value){
try{
this.redisTemplate.opsForHash().put(key, item, value);
return true;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
}
} /**
* 向一张hash表中放入数据,如果不存在将创建
* @param key
* @param item
* @param value
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return
*/
public boolean hset(String key, String item, Object value, long time){
try{
this.redisTemplate.opsForHash().put(key, item, value);
if (time > 0L)
this.expire(key, time);
return true;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
}
} /**
* 删除hash表中的值
* @param key
* @param item
*/
public void hdel(String key, Object...item){
this.redisTemplate.opsForHash().delete(key,item);
} /**
* 判断hash表里是否有改key值
* @param key
* @param item
* @return
*/
public boolean hHasKey(String key, String item){
return this.redisTemplate.opsForHash().hasKey(key, item);
} /**
* hash递增,如果不存在就会创建一个,并把新增的值返回
* @param key
* @param item
* @param by
* @return
*/
public double hincr(String key, String item, double by){
return this.redisTemplate.opsForHash().increment(key, item, by);
} /**
* hash递减,如果不存在就会创建一个,并把减少的值返回
* @param key
* @param item
* @param by
* @return
*/
public double hdecr(String key, String item, double by){
return this.redisTemplate.opsForHash().increment(key, item, -by);
} /**
* 根据key获取set中的所有值
* @param key
* @return
*/
public Set<Object> sGet(String key){
try {
return this.redisTemplate.opsForSet().members(key);
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return null;
}
} /**
* 根据value从一个set中查询是否存在
* @param key
* @param value
* @return
*/
public boolean sHasKey(String key, Object value){
try{
return this.redisTemplate.opsForSet().isMember(key, value);
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
}
} /**
* 将set数据放入缓存
* @param key
* @param values
* @return
*/
public long sSet(String key, Object... values){
try {
return this.redisTemplate.opsForSet().add(key,values);
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return 0L;
}
} /**
* 将set数据放入缓存
* @param key
* @param values
* @return
*/
public long sSetAndTime(String key, long time, Object... values){
try{
Long count = this.redisTemplate.opsForSet().add(key, values);
if (time > 0L){
this.expire(key, time);
}
return count;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return 0L;
}
} /**
* 获取set缓存数据的长度
* @param key
* @return
*/
public long sGetSetSize(String key){
try {
return this.redisTemplate.opsForSet().size(key);
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return 0L;
}
} /**
* 获取list缓存的内容
* @param key
* @param start
* @param end
* @return
*/
public List<Object> lGet(String key, long start, long end){
try{
return this.redisTemplate.opsForList().range(key, start, end);
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return null;
}
} /**
* 获取list缓存的长度
* @param key
* @return
*/
public long lGetListSize(String key){
try {
return this.redisTemplate.opsForList().size(key);
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return 0L;
}
} /**
* 通过索引 获取list缓存中的值
* @param key
* @param index
* @return
*/
public Object lGetIndex(String key, long index){
try {
return this.redisTemplate.opsForList().index(key, index);
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return 0L;
}
} /**
* 将list放入缓存
* @param key
* @param value
* @return
*/
public boolean lSet(String key, Object value){
try {
this.redisTemplate.opsForList().rightPush(key, value);
return true;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
}
}
public boolean lSet(String key, Object value, long time){
try {
this.redisTemplate.opsForList().rightPush(key, value);
if (time > 0L){
this.expire(key, time);
}
return true;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
}
}
public boolean lSet(String key,List<Object> value){
try {
this.redisTemplate.opsForList().rightPushAll(key, value);
return true;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
}
}
public boolean lSet(String key, List<Object> value, long time){
try {
this.redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0L){
this.expire(key, time);
}
return true;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
}
} /**
* 根据索引 修改list缓存中的某个数据
* @param key
* @param index
* @param value
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value){
try {
this.redisTemplate.opsForList().set(key, index, value);
return true;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return false;
}
} /**
* 移除n个值为value
* @param key
* @param count
* @param value
* @return
*/
public long lRemove(String key, long count, Object value){
try {
Long remove = this.redisTemplate.opsForList().remove(key, count, value);
return remove;
}catch (Exception e){
this.logger.error(ExceptionUtils.getStackTrace(e));
return 0L;
}
}
}
Redis和SpringBoot整合RedisUtils类的更多相关文章
- Redis和springboot 整合redisUtil类
一.引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...
- jackson学习之十(终篇):springboot整合(配置类)
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- 【SpringBoot | Redis】SpringBoot整合Redis
SpringBoot整合Redis 1. pom.xml中引入Redis相关包 请注意,这里我们排除了lettuce驱动,采用了jedis驱动 <!-- redis的依赖 --> < ...
- Redis-基本概念、java操作redis、springboot整合redis,分布式缓存,分布式session管理等
NoSQL的引言 Redis数据库相关指令 Redis持久化相关机制 SpringBoot操作Redis Redis分布式缓存实现 Resis中主从复制架构和哨兵机制 Redis集群搭建 Redis实 ...
- 【Redis】SpringBoot整合Redis
一.Maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId& ...
- Redis与SpringBoot整合
添加Redis相关jar包 <dependency> <groupId>org.springframework.boot</groupId> <artifac ...
- SpringBoot整合Redis使用Restful风格实现CRUD功能
前言 本篇文章主要介绍的是SpringBoot整合Redis,使用Restful风格实现的CRUD功能. Redis 介绍 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-valu ...
- jackson学习之九:springboot整合(配置文件)
欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 系列文章汇总 jackson学习之一:基本信息 jac ...
- SpringBoot整合Redis、mybatis实战,封装RedisUtils工具类,redis缓存mybatis数据 附源码
创建SpringBoot项目 在线创建方式 网址:https://start.spring.io/ 然后创建Controller.Mapper.Service包 SpringBoot整合Redis 引 ...
随机推荐
- pandas中的quantile函数
https://blog.csdn.net/weixin_38617311/article/details/87893168 data.price.quantile([0.25,0.5,0.75]) ...
- CTF隐写——越光宝盒
0x题目 原题来自于实验吧:http://www.shiyanbar.com/ctf/1992 一句话,和一个PNG图片. 0x解题 1.下载图片以后,发现打不开. 首先想到的就是文件头可能被修改了, ...
- 高博SLAM14讲 ch5 点云拼接例程实现与bug处理
一.环境配置,基本库的安装 1.Eigen库 apt-get 安装 2.sophus库 apt-get 安装 3.pcl 点云库 (1)官方预编译版本 sudo apt-get install lib ...
- Django框架(十七)—— 中间件、CSRF跨站请求伪造
目录 中间件 一.什么是中间件 二.中间件的作用 三.中间件执行顺序 四.自定义中间件 1.导包 2.定义类,继承MiddlewareMixin 3.在视图函数中定义一个函数 4.在settings的 ...
- Set 对象和WeakSet对象
Set对象是值的集合,你可以按照插入的顺序迭代它的元素. Set中的元素只会出现一次,即 Set 中的元素是唯一的,一种有效去重方式. , , , , ]); console.log(set1.has ...
- Java-技术专区-虚拟机系列-内存模型(JMM)
Java8内存模型—永久代(PermGen)和元空间(Metaspace) 一.JVM 内存模型 根据 JVM 规范,JVM 内存共分为虚拟机栈.堆.方法区.程序计数器.本地方法栈五个部 ...
- shiro安全框架的使用流程
最近学了shiro安全框架流程,在这里梳理一下shiro的工作流程和一些代码,方便以后使用的时候,能快速找到对应的代码. 要使用这个shiro框架,还要新建两张表 t_authority(权限表)和t ...
- 四、hibernate的缓存
缓存: 就是将数据保存到内存中,需要使用时直接从内存中获取,不需要每次查询数据库或者磁盘中的文件 hibernate的缓存 一级缓存:Session级别的缓存 二级缓存:SessionFactory级 ...
- navigator对象-了解
navigator 对象包含有关浏览器的信息,它有很多属性,我们最常用的是 userAgent ,该属性可以返回由客户机发送服务器的 user-agent 头部的值 下面前段代码可以判断用户使用哪个终 ...
- Codeforces 1166F 并查集 启发式合并
题意:给你一张无向图,无向图中每条边有颜色.有两种操作,一种是询问从x到y是否有双彩虹路,一种是在x到y之间添加一条颜色为z的边.双彩虹路是指:如果给这条路径的点编号,那么第i个点和第i - 1个点相 ...