基于SpringBoot3引入Redis并封装常用的操作RedisUtils

本文介绍了如何在SpringBoot3.x项目中集成Redis,包括下载和配置RedisForWindows,通过pom.xml引入依赖,配置application.yml,以及创建RedisUtils工具类进行常用操作的封装。作者还演示了如何使用Jackson2JsonRedisSerializer处理序列化和反序列化,以及简单的测试示例。
摘要由CSDN通过智能技术生成

基于SpringBoot3引入Redis并封装常用的操作RedisUtils,并提供简单使用示例。

系列文章指路👉

系列文章-基于SpringBoot3创建项目并配置常用的工具和一些常用的类

Redis For Windows下载

感谢大佬,链接放下面了:zkteco-home/redis-windows

简单配置

  1. 将Redis路径放入环境变量中

  2. 修改默认redis.conf 添加密码

save ""
port 6379 
requirepass '123456' 
maxmemory 256mb
appendonly no
maxmemory-policy allkeys-lru

以命令行的方法启动

# (也可以不带redis.conf,使用默认的配置启动) 
#  redis-server
redis-server redis.conf

在这里插入图片描述

以服务的方式启动

  1. 注册服务
# 注册服务
redis-server --service-install --service-name redisService1 redis.conf
  1. 启用、停止、删除服务
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
可以看到已经起来了,可以在属性中设置自动启动或者手动启动。
在这里插入图片描述

简单使用

  1. 进入命令行 redis-cli,设置了密码的话需要认证auth 123456
    在这里插入图片描述
  2. 存取示例:
    在这里插入图片描述

在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"));
    }

在这里插入图片描述
在这里插入图片描述
完事。


君子终日乾乾,夕惕若厉,无咎。

—— 《周易·易经·乾卦第一》

  • 25
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小雅痞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值