1、首先添加依赖,yml中配置redis
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
redis:
# Redis 服务器地址
host: 192.168.126.132
# 连接端口号
port: 6379
password: 123
# 数据库索引(0 - 15)
database: 0
# 连接超时时间(毫秒)
timeout: 10000
# lettuce 参数
lettuce:
pool:
# 最大连接数(使用负值表示没有限制) 默认为 8
max-active: 10
# 最大阻塞等待时间(使用负值表示没有限制) 默认为 -1 ms
max-wait: -1
# 最大空闲连接 默认为 8
max-idle: 5
# 最小空闲连接 默认为 0
min-idle: 0
2、redis配置文件
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.SocketOptions;
import io.lettuce.core.TimeoutOptions;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;
import java.time.Duration;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate (@Qualifier("lettuceConnectionFactory") LettuceConnectionFactory lettuceConnectionFactory){
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(lettuceConnectionFactory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 值采用json序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jackson2JsonRedisSerializer);
//初始化完成序列化的方法
/**必须执行这个函数,初始化RedisTemplate*/
template.afterPropertiesSet();
return template;
}
@Bean
public DefaultClientResources lettuceClientResources() {
return DefaultClientResources.create();
}
@Bean("lettuceConnectionFactory")
public LettuceConnectionFactory lettuceConnectionFactory(RedisProperties redisProperties, ClientResources clientResources, GenericObjectPoolConfig redisPoolConfig) {
ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
//按照周期刷新拓扑
.enablePeriodicRefresh(Duration.ofSeconds(10))
//根据事件刷新拓扑
.enableAllAdaptiveRefreshTriggers()
.build();
ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()
//redis命令超时时间,超时后才会使用新的拓扑信息重新建立连接
.autoReconnect(true)
.cancelCommandsOnReconnectFailure(false)
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.DEFAULT)
.pingBeforeActivateConnection(true)
.timeoutOptions(TimeoutOptions.enabled(redisProperties.getTimeout()))
.topologyRefreshOptions(topologyRefreshOptions)
.socketOptions(SocketOptions.builder().connectTimeout(redisProperties.getTimeout()).keepAlive(true).build())
.build();
LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
.clientResources(clientResources)
.clientOptions(clusterClientOptions)
.commandTimeout(redisProperties.getTimeout())
.shutdownTimeout(redisProperties.getLettuce().getShutdownTimeout())
.poolConfig(redisPoolConfig)
.build();
if(StringUtils.isEmpty(redisProperties.getCluster())){
//单机
RedisStandaloneConfiguration redisConfiguration = new RedisStandaloneConfiguration(redisProperties.getHost(),redisProperties.getPort());
redisConfiguration.setDatabase(redisProperties.getDatabase());
redisConfiguration.setPassword(redisProperties.getPassword());
LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisConfiguration, clientConfig);
lettuceConnectionFactory.afterPropertiesSet();
lettuceConnectionFactory.setValidateConnection(false);
return lettuceConnectionFactory;
}else {
//集群
RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());
clusterConfig.setMaxRedirects(redisProperties.getCluster().getMaxRedirects());
clusterConfig.setPassword(RedisPassword.of(redisProperties.getPassword()));
LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(clusterConfig, clientConfig);
lettuceConnectionFactory.afterPropertiesSet();
lettuceConnectionFactory.setValidateConnection(false);
return lettuceConnectionFactory;
}
}
/**
* Redis连接池配置</b>
*/
@Bean
public GenericObjectPoolConfig redisPoolConfig(RedisProperties redisProperties) {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxIdle(redisProperties.getLettuce().getPool().getMaxIdle());
poolConfig.setMinIdle(redisProperties.getLettuce().getPool().getMinIdle());
poolConfig.setMaxTotal(redisProperties.getLettuce().getPool().getMaxActive());
poolConfig.setMaxWaitMillis(redisProperties.getLettuce().getPool().getMaxWait().toMillis());
poolConfig.setTimeBetweenEvictionRunsMillis(100);
return poolConfig;
}
}
3、redis的工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
//@Component:定义Spring管理Bean(也就是将标注@Component注解的类交由spring管理)
//@AspectJ风格的切面可以通过@Compenent注解标识其为Spring管理Bean,
// 而@Aspect注解不能被Spring自动识别并注册为Bean,必须通过@Component注解来完成
@Component
public class RedisUtil {
@Autowired
RedisTemplate<String,Object> redisTemplate;
/**
* setex
* @param key key
* @param value value
* @param time 过期时间
*/
public void setex(String key,Object value,long time){
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}
/**
* set
* String类型的set,无过期时间
* @param key key
* @param value value
*/
public void set(String key, Object value){
redisTemplate.opsForValue().set(key,value);
}
/**
* 批量设置key和value
* @param map key和value的集合
*/
public void mset(Map<String,Object> map){
redisTemplate.opsForValue().multiSet(map);
}
/**
* 如果key不存在,则设置
* @param key key
* @param value value
* @return 返回是否成功
*/
public Boolean setnx(String key,Object value){
return redisTemplate.opsForValue().setIfAbsent(key, value);
}
/**
* 批量插入key,如果key不存在的话
* @param map key和value的集合
* @return 是否成功
*/
public Boolean msetnx(Map<String,Object> map){
return redisTemplate.opsForValue().multiSetIfAbsent(map);
}
/**
* String类型的get
* @param key key
* @return 返回value对应的对象
*/
public Object get(String key){
return redisTemplate.opsForValue().get(key);
}
/**
* 删除对应key
* @param key key
* @return 返回是否删除成功
*/
public Boolean del(String key){
return redisTemplate.delete(key);
}
/**
* 批量删除key
* @param keys key的集合
* @return 返回删除成功的个数
*/
public Long del(List<String> keys){
return redisTemplate.delete(keys);
}
/**
* 给某个key设置过期时间
* @param key key
* @param time 过期时间
* @return 返回是否设置成功
*/
public Boolean expire(String key, long time){
return redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
/**
* 返回某个key的过期时间
* @param key key
* @return 返回key剩余的过期时间
*/
public Long ttl(String key){
return redisTemplate.getExpire(key);
}
/**
* 返回是否存在该key
* @param key key
* @return 是否存在该key
*/
public Boolean exists(String key){
return redisTemplate.hasKey(key);
}
/**
* 给key的值加上delta值
* @param key key
* @param delta 参数
* @return 返回key+delta的值
*/
public Long incrby(String key, long delta){
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 给key的值减去delta
* @param key key
* @param delta 参数
* @return 返回key - delta的值
*/
public Long decrby(String key, long delta){
return redisTemplate.opsForValue().decrement(key, delta);
}
//hash类型
/**
* set hash类型
* @param key key
* @param hashKey hashKey
* @param value value
*/
public void hset(String key,String hashKey, Object value){
redisTemplate.opsForHash().put(key, hashKey, value);
}
/**
* set hash类型,并设置过期时间
* @param key key
* @param hashKey hashKey
* @param value value
* @param time 过期时间
* @return 返回是否成功
*/
public Boolean hset(String key, String hashKey,Object value, long time){
hset(key, hashKey, value);
return expire(key, time);
}
/**
* 批量设置hash
* @param key key
* @param map hashKey和value的集合
* @param time 过期时间
* @return 是否成功
*/
public Boolean hmset(String key, Map<String,Object> map, long time){
redisTemplate.opsForHash().putAll(key, map);
return expire(key, time);
}
/**
* 获取hash类型的值
* @param key key
* @param hashKey hashKey
* @return 返回对应的value
*/
public Object hget(String key, String hashKey){
return redisTemplate.opsForHash().get(key, hashKey);
}
/**
* 获取key下所有的hash值以及hashKey
* @param key key
* @return 返回数据
*/
public Map<Object,Object> hgetall(String key){
return redisTemplate.opsForHash().entries(key);
}
/**
* 批量删除
* @param key key
* @param hashKey hashKey数组集合
*/
public void hdel(String key, Object... hashKey){
redisTemplate.opsForHash().delete(key, hashKey);
}
/**
* 判断是否存在hashKey
* @param key key
* @param hashKey hashKey
* @return 是否存在
*/
public Boolean hexists(String key, String hashKey){
return redisTemplate.opsForHash().hasKey(key, hashKey);
}
}
4、redis工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
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.util.*;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
public static RedisTemplate redisTemplate;
/**
*
* 缓存基本的对象,Integer、String、实体类等
* @param key 缓存的键值
* @param value 缓存的值
* @param <T>
*/
public static <T> void setCacheObject(final String key, final T value){
redisTemplate.opsForValue().set(key, value);
}
/**
* 缓存基本的对象,Integer、String、实体类等
* @param key 缓存的键值
* @param value 缓存的值
* @param timeout 时间
* @param timeUnit 时间颗粒度
* @param <T>
*/
public static <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit){
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
/**
* 设置有效时间
*
* @param key key Redis键
* @param timeout timeout 超时时间
* @return true=设置成功;false=设置失败
*/
public static boolean expire(final String key, final long timeout){
return redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
/**
* 设置有效时间
* @param key key Redis键
* @param timeout timeout 超时时间
* @param unit unit 时间单位
* @return true=设置成功;false=设置失败
*/
public static boolean expire(final String key, final long timeout, TimeUnit unit){
return redisTemplate.expire(key, timeout, unit);
}
/**
* 获得缓存的基本对象。
* @param key key 缓存键值
* @return 缓存键值对应的数据
* @param <T>
*/
public static <T> T getCacheObject(final String key){
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
* 删除单个对象
* @param key
* @return
*/
public static boolean deleteObject(final String key){
return redisTemplate.delete(key);
}
/**
* 删除集合对象
* @param collection
* @return
*/
public static Long deleteObject(final Collection collection){
return redisTemplate.delete(collection);
}
/**
* 缓存List数据
* @param key 缓存的键值
* @param dataList 待缓存的List数据
* @return 缓存的对象
* @param <T>
*/
public static <T> long setCacheList(final String key, final List<T> dataList){
Long count = redisTemplate.opsForList().rightPushAll(key,dataList);
return count == null ? 0 : count;
}
/**
* 获得缓存的list对象
* @param key 缓存的键值
* @return 缓存键值对应的数据
* @param <T>
*/
public static <T> List<T> getCacheList(final String key){
return redisTemplate.opsForList().range(key, 0, -1);
}
/**
* 缓存Set
* @param key 缓存键值
* @param dataSet 缓存的数据
* @return 缓存数据的对象
* @param <T>
*/
public static <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet){
BoundSetOperations<String, T> setOperations = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator();
while (it.hasNext()){
setOperations.add(it.next());
}
return setOperations;
}
/**
* 获得缓存的set
* @param key
* @return
* @param <T>
*/
public static <T> Set<T> getCacheSet(final String key){
return redisTemplate.opsForSet().members(key);
}
/**
* 缓存Map
* @param key
* @param dataMap
* @param <T>
*/
public static <T> void setCacheMap(final String key, final Map<String, T> dataMap){
if(null != dataMap){
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
/**
* 获得缓存的Map
* @param key
* @return
* @param <T>
*/
public static <T> Map<String, T> getCacheMap(final String key){
return redisTemplate.opsForHash().entries(key);
}
/**
* 往Hash中存入数据
* @param key Redis键
* @param keyHash Hash键
* @param value 值
* @param <T>
*/
public static <T> void setCacheMapValue(final String key, final String keyHash, final T value){
redisTemplate.opsForHash().put(key, keyHash, value);
}
/**
* 获取Hash中的数据
* @param key Redis键
* @param hashKey Hash键
* @return Hash中的对象
* @param <T>
*/
public static <T> T getCacheMapValue(final String key, final String hashKey){
HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key,hashKey);
}
/**
* 删除Hash中的数据
*
* @param key
* @param hashKeys
*/
public static void delCacheMapValue(final String key, final String hashKeys)
{
HashOperations hashOperations = redisTemplate.opsForHash();
hashOperations.delete(key, hashKeys);
}
/**
* 获取多个Hash中的数据
*
* @param key Redis键
* @param hashKeys Hash键集合
* @return Hash对象集合
*/
public static <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hashKeys)
{
return redisTemplate.opsForHash().multiGet(key, hashKeys);
}
/**
* 获得缓存的基本对象列表
*
* @param pattern 字符串前缀
* @return 对象列表
*/
public static Collection<String> keys(final String pattern)
{
return redisTemplate.keys(pattern);
}
/**
* 为Redis中value对应的map增加value
* @param key 键值
* @param hashKey value-map对应的键值
* @param v value-map 对应的value值
*/
public static void incrementCacheMapValue(String key, String hashKey, int v){
redisTemplate.boundHashOps(key).increment(hashKey, v);
}
}