1、pom引入
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- redis.clients/jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
2、yml配置
2.1 单机版
spring:
redis:
host: 1xx.1xx.xxx.27
port: 63xx
password: FxxxxxxxxxxxxL
timeout: 5000
jedis:
pool:
# 连连接池的最大数据库连接数
max-active: 1200
# 连接池中的最大空闲连接
max-idle: 100
# 连接池中的最小空闲连接 默认为 0
min-idle: 10
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认为-1
max-wait: 30000
timeBetweenEvictionRunsMillis: 60000
# 向调用者输出“链接”对象时,是否检测它的空闲超时;
testWhileIdle: true
# 对于空闲链接检测线程而言,每次检测的链接资源的个数。默认为3.
numTestsPerEvictionRun: 20
2.2 集群版
spring:
redis:
cluster:
nodes: 10.xx.0.xx1:7000,10.xx.xx.xx9:7001,10.xx.xxx.xx8:7002
password:
timeout: 5000
# 重定向连接数
max-redirects: 3
jedis:
pool:
# 连连接池的最大数据库连接数
max-active: 1200
# 连接池中的最大空闲连接
max-idle: 100
# 连接池中的最小空闲连接 默认为 0
min-idle: 10
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认为-1
max-wait: 30000
timeBetweenEvictionRunsMillis: 60000
# 向调用者输出“链接”对象时,是否检测它的空闲超时;
testWhileIdle: true
# 对于空闲链接检测线程而言,每次检测的链接资源的个数。默认为3.
numTestsPerEvictionRun: 20
3、RedisConfig
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.*;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
import java.time.Duration;
import java.util.HashSet;
import java.util.Set;
/**
* Jedis连接池相关配置
*
* @author: zmm
* @date: 2021/04/01 11:35
*/
@Configuration
@EnableAutoConfiguration(exclude = {RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class}) // 注意exclude
public class RedisConfig {
// redis集群下
@Value("${spring.redis.cluster.nodes}")
private String host;
/* // redis单机
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;*/
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.timeout}")
private long timeout;
@Value("${spring.redis.max-redirects}")
private int redirects;
@Value("${spring.redis.jedis.pool.max-active}")
private int maxActive;
@Value("${spring.redis.jedis.pool.max-wait}")
private long maxWait;
@Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.jedis.pool.min-idle}")
private int minIdle;
@Value("${spring.redis.jedis.pool.timeBetweenEvictionRunsMillis}")
private long timeBetweenEvictionRuns;
@Value("${spring.redis.jedis.pool.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.redis.jedis.pool.numTestsPerEvictionRun}")
private int numTestsPer;
@Bean(name = "redisConnectionFactory")
public RedisConnectionFactory redisConnectionFactory() {
//redis环境配置:地址、端口、密码
/*
// 单机
RedisStandaloneConfiguration standaloneConfiguration = new RedisStandaloneConfiguration();
standaloneConfiguration.setHostName(host);
standaloneConfiguration.setPort(port);
standaloneConfiguration.setPassword(RedisPassword.of(password));
standaloneConfiguration.setDatabase(0);
*/
// 集群
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
String[] hosts = host.split(",");
Set<RedisNode> nodeList = new HashSet<>();
for (String hostAndPort : hosts) {
String[] hostOrPort = hostAndPort.split(":");
nodeList.add(new RedisNode(hostOrPort[0], Integer.parseInt(hostOrPort[1])));
}
redisClusterConfiguration.setClusterNodes(nodeList);
redisClusterConfiguration.setPassword(RedisPassword.of(password));
redisClusterConfiguration.setMaxRedirects(redirects);
// 获取jedis连接池的配置
JedisClientConfiguration jedisClientConfiguration = getJedisClientConfiguration();
return new JedisConnectionFactory(redisClusterConfiguration, jedisClientConfiguration);
}
// Must be configured, otherwise an error will be reported
@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplateObject = new RedisTemplate<String, Object>();
redisTemplateObject.setConnectionFactory(redisConnectionFactory());
setSerializer(redisTemplateObject);
redisTemplateObject.afterPropertiesSet();
return redisTemplateObject;
}
/**
* 设置jedis连接池
*
* @return JedisPoolConfig
*/
private JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(maxActive);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setMaxWaitMillis(maxWait);
poolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRuns);
//Checking validity at idle time
poolConfig.setTestWhileIdle(testWhileIdle);
poolConfig.setNumTestsPerEvictionRun(numTestsPer);
return poolConfig;
}
/**
* 获取Jedis客户端的配置
*
* @return JedisClientConfiguration
*/
private JedisClientConfiguration getJedisClientConfiguration() {
//构造jedis客户端配置
JedisClientConfiguration.JedisClientConfigurationBuilder builder = JedisClientConfiguration.builder();
Duration duration = Duration.ofMillis(timeout);
//超时配置
if (duration != null) {
builder.readTimeout(duration).connectTimeout(duration);
}
//修改连接池配置
builder.usePooling().poolConfig(jedisPoolConfig());
return builder.build();
}
/**
* 序列化键值的方式
*
* @param template
*/
private void setSerializer(RedisTemplate<String, Object> template) {
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
template.setKeySerializer(stringSerializer);
template.setValueSerializer(stringSerializer);
}
}
4、RedisUtils
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* 从redis中操作数据
*
* @author: zmm
* @date: 2021/04/01 12:12
*/
@Component
public class RedisUtils {
@Resource(name = "redisTemplate")
private RedisTemplate redisTemplate;
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public String get(String key) {
String value = (String) redisTemplate.opsForValue().get(key);
String[] split = value.split(";");
String times = split[split.length-1].split(",")[0];
RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
return key == null ? null : times;
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
return true;
} catch (Exception e) {
e.printStackTrace();
RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
return true;
} catch (Exception e) {
e.printStackTrace();
RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
return false;
}
}
/**
* 递增
* 将key值对应的value数值增加delta
* value必须为数值,否则会抛异常
*
* @param key 键
* @param delta 要增加几(大于0)
* @return 递增之后的value值
*/
public long increase(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
long value = redisTemplate.opsForValue().increment(key, delta);
RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
return value;
}
/**
* 递减
* 将key值对应的value数值增加delta
* value必须为数值,否则会抛异常
*
* @param key 键
* @param delta 要减少几(小于0)
* @return 递减之后的value值
*/
public long decrease(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
long value = redisTemplate.opsForValue().increment(key, -delta);
RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
return value;
}
}
5、RedisUtils - 全
链接: 摘自贴友.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @date : 2019/7/23 15:56
* Title : RedisUtil
* Description : redis工具类,提供了redis缓存操作的set/get相关方法(包括String/Hash/Set/List),所有的时间单位都是(秒)
* 1、如果redis中已经存在某个key,则redis对 Hash/Set/List 三种数据结构 的set操作都是追加操作,而不是覆盖原值,
* 如果需要覆盖原值,请先执行delete(key)方法删除原值;对于string类型,相同的key进行set操作是覆盖原值的;
* 2、redis 的 string 类型是二进制安全的,redis 的 string 可以包含任何数据,比如jpg图片或者序列化的对象;
* 所以基于以上两个特性,推荐使用string类型存储数据,譬如java中的list/map/对象类型都先转成string再存储到redis中。
*/
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
//=============================common============================
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean setExpire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void delete(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
//============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
* 将key值对应的value数值增加delta
* value必须为数值,否则会抛异常
*
* @param key 键
* @param delta 要增加几(大于0)
* @return 递增之后的value值
*/
public long increase(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
* 将key值对应的value数值增加delta
* value必须为数值,否则会抛异常
*
* @param key 键
* @param delta 要减少几(小于0)
* @return 递减之后的value值
*/
public long decrease(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
//================================Map=================================
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hashGet(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hashGet(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hashSet(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hashSet(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
setExpire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hashSet(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hashSet(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
setExpire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hashDel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hashHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hashIncrease(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hashDecrease(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
//============================set=============================
/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return
*/
public Set<Object> setGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean setHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long setSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long setSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0) {
setExpire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public long setGetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//===============================list=================================
/**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> listGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的所有内容
*
* @param key 键
* @return
*/
public List<Object> listGet(String key) {
return listGet(key, 0, -1);
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public long listGetSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object listGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean listSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean listSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
setExpire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean listSetList(String key, List value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean listSetList(String key, List value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
setExpire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean listUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long listRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}