相关依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.4.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.4.2</version>
</dependency>
<!--commons-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
配置文件
#Redis服务器地址
spring.redis.host=192.168.238.80
#Redis服务器连接端口
spring.redis.port=6379
#Redis数据库索引(默认为0)
spring.redis.database=0
#连接超时时间
spring.redis.timeout=1800000
#连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=20
#最大阻塞等待时间(复制表示没有限制)
spring.redis.lettuce.pool.max-wait=1
#连接池中的最大空间连接
spring.redis.lettuce.pool.max-idle=5
#连接池中的最小空间连接
spring.redis.lettuce.pool.min-idle=0
RedisConfig配置类
@AutoConfigureAfter(RedisAutoConfiguration.class)
@Configuration
@EnableCaching // 启用缓存,使用 Lettuce,自动注入配置的方式
public class RedisConfig extends CachingConfigurerSupport {
/**
* config RedisTemplate<Object, Object>
*/
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate (RedisConnectionFactory factory){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(factory);
// String 序列化方式
StringRedisSerializer stringSerializer = new StringRedisSerializer();
// Jackson 序列化方式
Jackson2JsonRedisSerializer jacksonSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSerializer.setObjectMapper(objectMapper);
// key 采用 stringSerializer,value 采用 jacksonSerializer
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(jacksonSerializer);
redisTemplate.setHashValueSerializer(jacksonSerializer);
return redisTemplate;
}
/**
* config CacheManager
*/
@Bean
@SuppressWarnings("all")
public CacheManager cacheManager(LettuceConnectionFactory factory) {
RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(factory);
RedisSerializationContext.SerializationPair pair =
RedisSerializationContext.SerializationPair.fromSerializer(
new Jackson2JsonRedisSerializer(Object.class));
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
// default set
// RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
return new RedisCacheManager(writer, config);
}
// 重新定义缓存 key 的生成策略
@Bean
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
Arrays.asList(params).stream().forEach(item -> {
sb.append(item.toString());
});
return sb.toString();
}
};
}
}
RedisUtil工具类
@Component
public class RedisUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtils.class);
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* count > 0:从左到右删除等于value的第一个元素
* count = 0:删除等于value的所有元素
* count < 0:从右到左删除等于value的第一个元素
*/
public long removeListItem(String key, long count, Object value) {
try {
return redisTemplate.opsForList().remove(key, count, value);
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return 0;
}
}
public boolean updateListItem(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return false;
}
}
public boolean setList(String key, List<Object> list) {
try {
redisTemplate.opsForList().rightPushAll(key, list);
return true;
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return false;
}
}
public boolean setListItem(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return false;
}
}
public Object getListItem(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return null;
}
}
public long getListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return 0;
}
}
public List<Object> getListRang(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return null;
}
}
public long removeSetMembers(String key, Object... setValues) {
try {
return redisTemplate.opsForSet().remove(key, setValues);
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return 0;
}
}
public long setSetMembers(String key, long timeOut, Object... values) {
try {
long count = redisTemplate.opsForSet().add(key, values);
if (timeOut > 0) {
expire(key, timeOut);
}
return count;
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return 0;
}
}
public long setSetMembers(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return 0;
}
}
public long getSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return 0;
}
}
public boolean isSetMember(String key, Object setValue) {
return redisTemplate.opsForSet().isMember(key, setValue);
}
public Set<Object> getSet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return null;
}
}
public boolean putHash(String key, Map<String, Object> hashObject,
long timeOut) {
try {
redisTemplate.opsForHash().putAll(key, hashObject);
if (timeOut > 0) {
expire(key, timeOut);
}
return true;
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return false;
}
}
public boolean putHash(String key, Map<String, Object> hashObject) {
try {
redisTemplate.opsForHash().putAll(key, hashObject);
return true;
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return false;
}
}
public Map<Object, Object> getHash(String key) {
return redisTemplate.opsForHash().entries(key);
}
@SuppressWarnings("all")
public void deleteHashItems(String key, String... hashKeys) {
redisTemplate.opsForHash().delete(key, hashKeys);
}
public boolean haveHahsKey(String key, String hashKey) {
return redisTemplate.opsForHash().hasKey(key, hashKey);
}
public double decrementHash(String key, String hashKey, double delta) {
return redisTemplate.opsForHash().increment(key, hashKey, -delta);
}
public double incrementHash(String key, String hashKey, double delta) {
return redisTemplate.opsForHash().increment(key, hashKey, delta);
}
public boolean putHashValue(String key, String hashKey, Object hashValue, long timeOut) {
try {
redisTemplate.opsForHash().put(key, hashKey, hashValue);
if (timeOut > 0) {
expire(key, timeOut);
}
return true;
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return false;
}
}
public boolean putHashValue(String key, String hashKey, Object hashValue) {
try {
redisTemplate.opsForHash().put(key, hashKey, hashValue);
return true;
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return false;
}
}
public Object getHashValue(String key, String hashKey) {
return redisTemplate.opsForHash().get(key, hashKey);
}
// 设置value递减
public long decrement(String key, long delta) {
if (delta < 1) {
throw new RuntimeException("Increment delta must great than 0.");
}
return redisTemplate.opsForValue().decrement(key, delta);
}
// 设置value递增
public long increment(String key, long delta) {
if (delta < 1) {
throw new RuntimeException("Increment delta must great than 0.");
}
return redisTemplate.opsForValue().increment(key, delta);
}
public boolean set(String key, Object value, long timeOut) {
try {
if (timeOut > 0) {
redisTemplate.opsForValue().set(key, value, timeOut, TimeUnit.SECONDS);
} else {
redisTemplate.opsForValue().set(key, value);
}
return true;
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return false;
}
}
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return false;
}
}
public Object get(String key) {
return StringUtils.isBlank(key) ? null : redisTemplate.opsForValue().get(key);
}
public void delete(String... key) {
if (null != key && key.length > 0) {
redisTemplate.delete(Stream.of(key).collect(Collectors.toList()));
}
}
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return false;
}
}
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
// 设置过期时间
public boolean expire(String key, long timeOut) {
try {
if (timeOut > 0) {
redisTemplate.expire(key, timeOut, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
LOGGER.debug(e.getMessage());
return false;
}
}
}
RedisController
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping
public String testRedis(){
//设置值到redis
redisTemplate.opsForValue().set("name","lucy");
//获取值
String name =(String) redisTemplate.opsForValue().get("name");
return name;
}
}
结果