1.pom文件需要引入的jar
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.3</version>
</dependency>
2.redis.properties文件
redis.cache_pool_flag=yes
redis.cache_pool_max_active=300
redis.cache_pool_max_idle=50
redis.cache_pool_max_wait=10000
redis.cache_server_ip=********
redis.cache_server_port=****
redis.cache_server_auth=*****
redis.cache_server_timeout=6000
redis.cache_pool_test_on_borrow=false
redis.cache_server_dbindex=3
redis.CacheKeyPrefix=pole_operation_
3.读取配置文件类
@Data
@Component
@ConfigurationProperties(prefix = "redis",ignoreUnknownFields = false)
@PropertySource(value = "classpath:redis.properties",encoding = "UTF-8")
public class RedisProperties {
@Value("${redis.cache_server_ip}")
private String cache_server_ip;
@Value("${redis.cache_server_port}")
private int cache_server_port;
@Value("${redis.cache_server_auth}")
private String cache_server_auth;
@Value("${redis.cache_server_dbindex}")
private int cache_server_dbindex;
@Value("${redis.CacheKeyPrefix}")
private String CacheKeyPrefix;
@Value("${redis.cache_server_timeout}")
private int cache_server_timeout;
@Value("${redis.cache_pool_max_active}")
private int cache_pool_max_active;
@Value("${redis.cache_pool_max_idle}")
private int cache_pool_max_idle;
@Value("${redis.cache_pool_max_wait}")
private int cache_pool_max_wait;
@Value("${redis.cache_pool_flag}")
private String cache_pool_flag;
@Value("${redis.cache_pool_test_on_borrow}")
private String cache_pool_test_on_borrow;
}
4.redisconfig初始化配置类
package com.newfiber.config;
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
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.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.ObjectUtils;
import java.time.Duration;
/**
* redis配置
* @author :
*/
@Configuration
@EnableCaching //开启缓存支持
public class RedisConfig extends CachingConfigurerSupport {
@Autowired
private RedisProperties redisProperties;
/**
* 本地数据源 redis template
*
* @return
*/
@Bean
public RedisTemplate redisTemplate() {
/* ========= 基本配置 ========= */
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName(redisProperties.getCache_server_ip());
configuration.setPort(redisProperties.getCache_server_port());
configuration.setDatabase(redisProperties.getCache_server_dbindex());
if (!ObjectUtils.isEmpty(redisProperties.getCache_server_auth())) {
RedisPassword redisPassword = RedisPassword.of(redisProperties.getCache_server_auth());
configuration.setPassword(redisPassword);
}
/* ========= 连接池通用配置 ========= */
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setMaxTotal(redisProperties.getCache_pool_max_active());
genericObjectPoolConfig.setMaxIdle(redisProperties.getCache_pool_max_idle());
genericObjectPoolConfig.setMaxWaitMillis(redisProperties.getCache_pool_max_wait());
/* ========= lettuce pool ========= */
LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder builder = LettucePoolingClientConfiguration.builder();
builder.poolConfig(genericObjectPoolConfig);
builder.commandTimeout(Duration.ofSeconds(redisProperties.getCache_server_timeout()));
LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration, builder.build());
factory.afterPropertiesSet();
/* ========= 创建 template ========= */
return createRedisTemplate(factory);
}
/**
* 重新lettuceConnectionFactory
* @return
*/
@Bean
public LettuceConnectionFactory lettuceConnectionFactory() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setDatabase(redisProperties.getCache_server_dbindex());
configuration.setHostName(redisProperties.getCache_server_ip());
configuration.setPort(redisProperties.getCache_server_port());
if (!ObjectUtils.isEmpty(redisProperties.getCache_server_auth())) {
RedisPassword redisPassword = RedisPassword.of(redisProperties.getCache_server_auth());
configuration.setPassword(redisPassword);
}
LettuceClientConfiguration.LettuceClientConfigurationBuilder builder = LettuceClientConfiguration.builder();
LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration,builder.build());
return factory;
}
@Bean
@Override
public KeyGenerator keyGenerator() {
return (o, method, objects) -> {
StringBuilder sb = new StringBuilder(32);
sb.append(o.getClass().getSimpleName());
sb.append(".");
sb.append(method.getName());
if (objects.length > 0) {
sb.append("#");
}
String sp = "";
for (Object object : objects) {
sb.append(sp);
if (object == null) {
sb.append("NULL");
} else {
sb.append(object.toString());
}
sp = ".";
}
return sb.toString();
};
}
/** key和value的序列化器 */
public RedisSerializationContext.SerializationPair<String> STRING_PAIR = RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer());
public RedisSerializationContext.SerializationPair<Object> FASTJSON_PAIR = RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer());
@Bean
@Override
public CacheManager cacheManager() {
// 初始化一个RedisCacheWriter
RedisCacheWriter cacheManager = RedisCacheWriter.nonLockingRedisCacheWriter(lettuceConnectionFactory());
// 设置默认过期时间:3 分钟
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(3))
.serializeKeysWith(STRING_PAIR)
.serializeValuesWith(FASTJSON_PAIR)
.disableCachingNullValues();
RedisCacheManager redisCacheManager = new RedisCacheManager(cacheManager, defaultCacheConfig);
return redisCacheManager;
}
/**
* json 实现 redisTemplate
* <p>
* 该方法不能加 @Bean 否则不管如何调用,connectionFactory都会是默认配置
*
* @param redisConnectionFactory
* @return
*/
public RedisTemplate createRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
5.redisUtil类,业务功能代码中直接使用
package com.newfiber.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Created by Administrator on 2018/6/14.
*
* @Project_name:springboot_xf
* @LOCAL:com.xf.water.springboot_mongdb.config.redis
* @blog : http://www.cnblog,com/huhongy/
* @description:redis的通用方法
*/
@Component
public class RedisUtils {
@Autowired
private RedisTemplate redisTemplate;
/**
* @author huhy
* @ClassName:RedisUtils
* @date 2018/8/4 16:57
* @Description: 切换redis库 0---15
* 注意,集群下这个方法报错 默认是o号库
*/
/*public void changeDatabase(int i){
JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
redisConnectionFactory.setDatabase(i);
redisTemplate.setConnectionFactory(redisConnectionFactory);
}*/
/**
* 写入缓存
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
/*boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;*/
return set(key,value,60L);
}
/**
* 写入缓存设置时效时间
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public boolean setWithOutExpire(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 批量删除对应的value
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0){
redisTemplate.delete(keys);
}
}
/**
* 删除对应的value
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 哈希 添加
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key,hashKey,value);
}
/**
* 哈希获取数据
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key,hashKey);
}
/**
* 列表添加
* @param k
* @param v
*/
public void lPush(String k,Object v){
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k,v);
}
/**
* 列表获取
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> lRange(String k, long l, long l1){
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k,l,l1);
}
/**
* 集合添加
* @param key
* @param value
*/
public void add(String key,Object value){
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key,value);
}
/**
* 集合获取
* @param key
* @return
*/
public Set<Object> setMembers(String key){
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* 有序集合添加
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key,Object value,double scoure){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key,value,scoure);
}
/**
* 有序集合获取
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByScore(String key,double scoure,double scoure1){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
}