问题背景
redis常用的工具类
注意事项:
- 默认已安装redis,可以使用安装包安装看这篇文章,使用docker安装看这篇文章
- 可以直接使用本文代码自己创建工程,也可以直接下载源码进行参考
项目搭建
1 添加pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yg</groupId>
<artifactId>redisson</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>redisson</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<!-- <scope>test</scope>-->
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.1</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-configuration-processor</artifactId>-->
<!-- <optional>true</optional>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.16.8</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2 配置redisTemplate容器bean
package com.yg.redisson.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @Author suolong
* @Date 2022/4/26 13:38
* @Version 2.0
*/
@Configuration
public class RedisConfig {
@Autowired
private RedisProperties redisProperties;
// @Bean
// public JedisCluster getJedisCluster(){
// final String[] split = redisProperties.getNodes().split(",");
// final HashSet<HostAndPort> nodes = new HashSet<>();
// for (String ipPort : split) {
// final String[] pair = ipPort.split(":");
// nodes.add(new HostAndPort(pair[0].trim(), Integer.parseInt(pair[1].trim())));
// }
// return new JedisCluster(nodes, redisProperties.getCommandTimeout(),new JedisPoolConfig());
// }
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
3 读取application的redis端口和IP配置
package com.yg.redisson.config;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Author suolong
* @Date 2022/4/26 13:34
* @Version 2.0
*/
@Component
//@ConfigurationProperties(prefix = "spring.redis.cluster") // 集群配置
@ConfigurationProperties(prefix = "spring.redis") //单机配置
@Data
@NoArgsConstructor
public class RedisProperties {
//集群节点和超时时间
// private String nodes;
// private int commandTimeout;
//单机配置
private String host;
private int port;
}
4 分布式锁Redisson配置
package com.yg.redisson.config;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author suolong
* @Date 2022/4/26 13:33
* @Version 2.0
*/
@Configuration
@Slf4j
public class RedissonConfig {
@Autowired
RedisProperties redisProperties;
private static final String REDISSON_PREFIX = "redis://";
@Bean
public RedissonClient redissonClusterClient(){
final Config config = new Config();
//redis集群配置
// final String[] split = redisProperties.getNodes().split(",");
// List<String> clusterIpPorts = Lists.newArrayList();
// for (String ipPort : split) {
// clusterIpPorts.add(String.format("%s%s", REDISSON_PREFIX, ipPort));
// }
//
// config.useClusterServers()
// .setScanInterval(2000)
// .addNodeAddress(String.join(",", clusterIpPorts));
//redis单机配置
config.useSingleServer().setAddress(String.format("%s%s:%s",REDISSON_PREFIX,redisProperties.getHost(),redisProperties.getPort()));
try {
return Redisson.create(config);
}catch (Exception ex){
log.error("RedissonClient init Exception", ex);
return null;
}
}
}
5 redisUtils工具类
package com.yg.redisson.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* @Author suolong
* @Date 2022/4/26 13:33
* @Version 2.0
*/
@Service("redisUtils")
@Slf4j
public class RedisUtils {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
public Object get(String key) {
try {
return key == null null : redisTemplate.opsForValue().get(key);
}catch (Exception ex){
log.error("获取缓存异常", ex);
return null;
}
}
public boolean del(String key){
try {
return Boolean.TRUE.equals(redisTemplate.delete(key));
}catch (Exception e){
log.error("删除缓存键异常",e);
return false;
}
}
public Long increment(String key, Long delta){
try {
return redisTemplate.opsForValue().increment(key, delta);
}catch (Exception ex){
log.error("操作缓存异常",ex);
return null;
}
}
public void saveByPipeLine(Map<String, Map<String, String>> dataMap){
try {
final RedisSerializer keySerializer = redisTemplate.getKeySerializer();
final RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
redisTemplate.executePipelined((RedisCallback<Object>) redisConnection -> {
dataMap.forEach((key,value) -> redisConnection.set(Objects.requireNonNull(keySerializer.serialize(key)), Objects.requireNonNull(valueSerializer.serialize(value)), Expiration.seconds(6 * 3600), RedisStringCommands.SetOption.UPSERT));
return null;
});
}catch (Exception ex){
log.error("pipeline存储异常",ex);
}
}
public void saveByPipeLineMap(Map<String, String> dataMap, String key){
try {
final RedisSerializer keySerializer = redisTemplate.getKeySerializer();
final RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
redisTemplate.executePipelined((RedisCallback<Object>) redisConnection -> {
redisConnection.set(Objects.requireNonNull(keySerializer.serialize(key)), Objects.requireNonNull(valueSerializer.serialize(dataMap)), Expiration.seconds(6 * 3600), RedisStringCommands.SetOption.UPSERT);
return null;
});
}catch (Exception ex){
log.error("pipeline存储异常",ex);
}
}
public List<Object> getByPipeLine(List<String> keys){
try {
return redisTemplate.executePipelined((RedisCallback<Object>) redisConnection -> {
for (String key : keys) {
redisConnection.get(key.getBytes(StandardCharsets.UTF_8));
}
return null;
});
}catch (Exception ex){
log.error("pipeline读取异常",ex);
}
return Collections.emptyList();
}
/**
* 普通缓存放入
* @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();
log.error("设置缓存异常:{}",e.getLocalizedMessage());
return false;
}
}
public Long del(Set<String> key) {
try {
if (CollectionUtils.isNotEmpty(key)) {
return redisTemplate.delete(key);
}
return null;
}catch (Exception ex){
log.error("删除缓存键异常:{}", ex.getLocalizedMessage());
return null;
}
}
public boolean setNX(String lockKey, String value, long expiryTime) {
if (redisTemplate == null) {
log.info("redisTemplate is null");
return false;
}
try {
Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, value, expiryTime, TimeUnit.SECONDS);
assert flag != null;
if (!flag) {
log.info("加锁失败");
return false;
}
log.info("Thread [{}] redisTemplate lock [{}] success", Thread.currentThread().getName(), lockKey);
// 加锁成功
return true;
} catch (Exception e) {
log.info("加锁失败", e);
log.error("redisTemplate lock [{}] Exception:", lockKey, e);
return false;
}
}
}
6 启动类
package com.yg.redisson;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RedissonApplication {
public static void main(String[] args) {
SpringApplication.run(RedissonApplication.class, args);
}
}
7 application.yml配置文件
spring:
redis:
host: 10.10.196.249
port: 6379
jedis:
pool:
max-active: 300
max-idle: 8
profiles:
active: prod
8 application.properties配置文件
#集群配置
spring.redis.cluster.nodes= 127.0.0.1:7000,127.0.0.1:7001,127.0.0.1:7002
spring.redis.cluster.command-timeout=5000
9 测试类
package com.yg.redisson.main;
import com.yg.redisson.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @Author suolong
* @Date 2022/4/26 13:48
* @Version 2.0
*/
@Slf4j
@SpringBootTest
public class RedissonTest {
@Autowired
RedisUtils redisUtils;
@Test
void redisSet() {
boolean res = redisUtils.set("yuan", "gao");
log.info("res: {}", res);
}
}
10 项目文件目录
代码测试
1 运行Test
2 查看redis客户端
总结
- redis常用工具类方便操作
作为程序员第 116 篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha ...