一、引入依赖

<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类的更多相关文章

  1. Redis和springboot 整合redisUtil类

    一.引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  2. jackson学习之十(终篇):springboot整合(配置类)

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  3. 【SpringBoot | Redis】SpringBoot整合Redis

    SpringBoot整合Redis 1. pom.xml中引入Redis相关包 请注意,这里我们排除了lettuce驱动,采用了jedis驱动 <!-- redis的依赖 --> < ...

  4. Redis-基本概念、java操作redis、springboot整合redis,分布式缓存,分布式session管理等

    NoSQL的引言 Redis数据库相关指令 Redis持久化相关机制 SpringBoot操作Redis Redis分布式缓存实现 Resis中主从复制架构和哨兵机制 Redis集群搭建 Redis实 ...

  5. 【Redis】SpringBoot整合Redis

    一.Maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId& ...

  6. Redis与SpringBoot整合

    添加Redis相关jar包 <dependency> <groupId>org.springframework.boot</groupId> <artifac ...

  7. SpringBoot整合Redis使用Restful风格实现CRUD功能

    前言 本篇文章主要介绍的是SpringBoot整合Redis,使用Restful风格实现的CRUD功能. Redis 介绍 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-valu ...

  8. jackson学习之九:springboot整合(配置文件)

    欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 系列文章汇总 jackson学习之一:基本信息 jac ...

  9. SpringBoot整合Redis、mybatis实战,封装RedisUtils工具类,redis缓存mybatis数据 附源码

    创建SpringBoot项目 在线创建方式 网址:https://start.spring.io/ 然后创建Controller.Mapper.Service包 SpringBoot整合Redis 引 ...

随机推荐

  1. thinkphp 连接多个数据库

    config配置文件 //数据库配置信息 'DB_CONFIG' => array( 'DB_TYPE' => 'mysql', // 数据库类型 'DB_HOST' => 'loc ...

  2. 12. MySQL简单使用

    关于MySQL的使用,大家可以去网上看相关教程,但是为了保证阅读的连贯性,这里会做简单介绍. 创建数据库 我们双击刚刚新建的数据库,然后双击mysql,点击新建查询,可以在编辑器里面输入一些mysql ...

  3. Rust <4>:所有权、借用、切片

    tips:栈内存分配大小固定,访问时不需要额外的寻址动作,故其速度快于堆内存分配与访问. rust 所有权规则: 每一个值在任意时刻都有且只有唯一一个所有者 当所有者离开作用域时,这个值将被丢弃 所有 ...

  4. yum常见问题

    --> Finished Dependency Resolution Error: Multilib version problems found. This often means that ...

  5. PAT甲级——A1150 TravellingSalesmanProblem【25】

    The "travelling salesman problem" asks the following question: "Given a list of citie ...

  6. jmeter 不同线程组之间传递变量2

    方法1  通过变量传递参数: 第一个脚本: HTTP Request_新建出差申请单_登录,关联出参数token.companyId.userId.userName 1.添加后置处理器:BeanShe ...

  7. 在doker上的python安装及环境部署

    python环境部署 我们今天学习的内容是如何将Django项目部署到linux服务器上,我们部署的linux系统是centos7首先,我们先在linux上搭建我们的Python3环境: 在这里首先强 ...

  8. 27-python基础-python3-异常处理(try except)

    到目前为止,在 Python 程序中遇到错误,或“异常”,意味着整个程序崩溃.不希望这发生在真实世界的程序中. 相反,希望程序能检测错误,处理它们,然后继续运行.   实例1: 当试图用一个数除以零时 ...

  9. Python之向函数传递元组和字典

    也可以在函数定义时加上这两个参数用以接收多余的参数哦~

  10. ASE——第一次结对作业

    ASE--第一次结对作业 问题定义 很早就听说了MSRA的黄金点游戏,让大家写Bot来参加比赛看谁的AI比较聪明可以操盘割韭菜.深感ASE课程老师设计的任务太用心了,各种接口都准备好了,大家只用专注于 ...