基于SpringBoot3引入Redis并封装常用的操作RedisUtils
基于SpringBoot3引入Redis并封装常用的操作RedisUtils,并提供简单使用示例。安装Redis Windows并提供简单使用样例
·
基于SpringBoot3引入Redis并封装常用的操作RedisUtils,并提供简单使用示例。
系列文章指路👉
系列文章-基于SpringBoot3创建项目并配置常用的工具和一些常用的类
文章目录
Redis For Windows下载
感谢大佬,链接放下面了:zkteco-home/redis-windows
简单配置
-
将Redis路径放入环境变量中
-
修改默认
redis.conf添加密码
save ""
port 6379
requirepass '123456'
maxmemory 256mb
appendonly no
maxmemory-policy allkeys-lru
以命令行的方法启动
# (也可以不带redis.conf,使用默认的配置启动)
# redis-server
redis-server redis.conf

以服务的方式启动
- 注册服务
# 注册服务
redis-server --service-install --service-name redisService1 redis.conf
- 启用、停止、删除服务
redis-server --service-start --service-name redisService1
redis-server --service-stop --service-name redisService1
redis-server --service-uninstall --service-name redisService1

3. WINDOWS + R 输入 services.msc
可以看到已经起来了,可以在属性中设置自动启动或者手动启动。
简单使用
- 进入命令行
redis-cli,设置了密码的话需要认证auth 123456
- 存取示例:

在Spring Boot中引入Redis
pom.xml 引入依赖
<!-- 集成redis依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- redis 连接池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
application.yml修改配置
spring:
data:
redis:
host: localhost
port: 6379
password: 123456
database: 0
lettuce:
pool:
min-idle: 0
max-idle: 8
max-wait: -1ms
max-active: 16
配置序列化方式
使用默认的序列化方式,在可视化工具中查看已经存入的key/value 很困难。
package com.ya.boottest.utils.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
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;
/**
* <p>
* Redis 配置类
* </p>
*
* @author Ya Shi
* @since 2024/3/12 14:21
*/
@Configuration
public class YaRedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// 设置objectMapper:转换java对象的时候使用
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.activateDefaultTyping( LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(objectMapper, Object.class);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// 设置key/value值的序列化方式
template.setKeySerializer(stringRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
编写工具类 RedisUtils
package com.ya.boottest.utils.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
/**
* <p>
* Redis 工具类
* </p>
*
* @author Ya Shi
* @since 2024/3/12 14:02
*/
@Component
public class RedisUtils {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private static final Long RELEASE_SUCCESS = 1L;
private static final String RELEASE_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
"return redis.call('del', KEYS[1]) " +
"else " +
"return 0 " +
"end";;
// 设置键值对
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
// 设置键值对并指定过期时间
public void set(String key, Object value, long timeout, TimeUnit unit) {
redisTemplate.opsForValue().set(key, value, timeout, unit);
}
// 设置键值对并指定过期时间
public void set(String key, Object value, long seconds) {
redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
}
// 获取值
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
// 获取值
public String getString(String key) {
Object obj = redisTemplate.opsForValue().get(key);
return obj == null ? null : obj.toString();
}
// 删除键
public Boolean delete(String key) {
return redisTemplate.delete(key);
}
// 判断键是否存在
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
// 如果不存在,则设置
public Boolean setNx(String key, Object value) {
return redisTemplate.opsForValue().setIfAbsent(key, value);
}
// 如果不存在,则设置,附带过期时间
public Boolean tryLock(String lockKey, String requestId, long seconds) {
return redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, seconds, TimeUnit.SECONDS);
}
// 如果不存在,则设置,附带过期时间
public Boolean tryLock(String lockKey, String requestId, long timeout, TimeUnit unit) {
return redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, timeout, unit);
}
// 不存在返回true,存在则删除
public Boolean releaseLock(String lockKey, String requestId){
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
redisScript.setScriptText(RELEASE_SCRIPT);
redisScript.setResultType(Long.class);
Long result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), Collections.singletonList(requestId));
return RELEASE_SUCCESS.equals(result);
}
}
简单测试
@Autowired
RedisUtils redisUtils;
@Test
void contextLoads() {
redisUtils.set("test:key:name", "xxxxxx");
redisUtils.set("test:key:name2", "yyyyy");
System.out.println(redisUtils.getString("test:key:name2"));
}


完事。
君子终日乾乾,夕惕若厉,无咎。
—— 《周易·易经·乾卦第一》
更多推荐


所有评论(0)