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 引 ...
随机推荐
- User control's property loses value after a postback
User control's property loses value after a postback All variables (and controls) are disposed at th ...
- linux 日志文件查看
记录下日志中常用的日志查看命令. 1. tail -n 10 -f **.log 显示日志文件尾部10行日志,当有新日志产生,会追加显示. 2. tail 命令 现ff.sh中有如下信息: [ro ...
- 用 Flask 来写个轻博客 (8) — (M)VC_Alembic 管理数据库结构的升级和降级
Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 扩展阅读 Alembic 查看指令 manager db 的可用选项 ...
- Linux中TLS
TLS(Thread Local Storage) 线程局部存储. 在Linux操作系统中,TLS保存成GDT中描述的一个段. 1: /* 2: * This creates a new proces ...
- 力扣算法——141LinkedListCycel【E】
Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked lis ...
- spring data jpa 使用JPQL的方式查询
用Spring Data JPA提供的查询方法已经可以解决大部分的应用场景,但是对于某些业务来说,我们还需要灵活的构造查询条件,这时就可以使用@Query注解,结合JPQL的语句方式完成查询 @Que ...
- mysql的时间存储格式
虽然mysql提供了datatime和timestamp两种存储时间的格式,但是如果设计较多计算,应存INT(11)类型.
- 微信小程序 获取用户信息并保存登录状态
微信小程序 获取用户信息并保存登录状态:http://www.360doc.com/content/18/0124/11/9200790_724662071.shtml
- SiteMesh 2.X 的使用(网页结构模板)
SiteMesh是基于Servlet的filter的,即过滤流.它是通过截取reponse,并进行装饰后再交付给客户. 其中涉及到两个名词: 装饰页面(decorator page)和 "被 ...
- SpringCloud:基础
SpringCloud:基础 SpringCloud 是微服务架构的一个实现框架,说他是一个框架更不如说他是一个生态,他包含了很多个技术,将这些技术组合起来形成我们的微服务架构应用. 1.Spring ...