springboot3整合redis

来源于https://www.bilibili.com/video/BV1UC41187PR/?spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=865f32e12aef524afb83863069b036aa

一、整合redis

1.创建项目文件

2.添加依赖
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</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>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.5</version>
        </dependency>
        <!-- mybatis-plus会自动调用mybatis,但mybatis-spring版本和springboot3+版本的spring会不匹配,所以要升版本-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>3.0.3</version>
        </dependency>
    </dependencies>
3.配置文件

后缀名改为yml

配置redis、mysql数据源、日志

server:
  port: 9999

spring:
  data:
    redis:
      port: 6379
      host: localhost

  datasource:
    username: root
    password: *****
    url: jdbc:mysql:///testdb
    
logging:
  level:
    com.qqcn: debug
4.创建redis配置类

@EnableCaching该注解为启动缓存管理

redisTemplate对象用来操作redis

redisCacheManager缓存管理器

其中setKey(Serializer)序列化 存到redis中的数据更加直观

package com.qqcn.config;

import org.springframework.cache.annotation.EnableCaching;
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.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        return redisTemplate;
    }

    @Bean
    public RedisCacheManager redisCacheManager(RedisTemplate<String, Object> redisTemplate) {  // 明确指定参数化类型
        if (redisTemplate == null || redisTemplate.getConnectionFactory() == null) {
            // 处理错误情况,例如抛出异常或采取默认行为
            throw new RuntimeException("RedisTemplate or its connection factory is null");
        }
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.n
### 整合 Redis 到 Spring Boot 3 的教程 在现代应用程序开发中,Redis 是一种广泛使用的内存数据存储解决方案。通过将其集成到 Spring Boot 应用程序中,可以显著提高性能并支持缓存功能。以下是关于如何在 Spring Boot 3整合 Redis 的详细说明。 #### 配置依赖项 为了使 Spring Boot 和 Redis 能够协同工作,需要引入必要的 Maven 或 Gradle 依赖项。这些依赖项提供了与 Redis 进行交互所需的功能库[^1]。 对于 Maven 构建工具,可以在 `pom.xml` 文件中添加以下内容: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- 如果计划使用 Lettuce 客户端 --> <dependency> <groupId>io.lettuce.core</groupId> <artifactId>lettuce-core</artifactId> </dependency> ``` 如果项目基于 Gradle,则应在 `build.gradle` 文件中加入如下配置: ```gradle implementation &#39;org.springframework.boot:spring-boot-starter-data-redis&#39; // 可选:Lettuce 客户端 implementation &#39;io.lettuce.core:lettuce-core&#39; ``` 上述依赖会自动导入所需的类和方法来操作 Redis 数据库[^2]。 --- #### 配置文件设置 完成依赖项的添加之后,在项目的 `application.properties` 或者 `application.yml` 文件中定义 Redis 的连接参数。例如: ##### 使用 application.properties: ```properties spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= spring.redis.database=0 ``` ##### 使用 application.yml: ```yaml spring: redis: host: localhost port: 6379 password: "" database: 0 ``` 以上属性指定了 Redis 实例的位置以及访问权限等信息[^3]。 --- #### 创建 Redis 配置类 可以通过创建自定义配置类进一步调整默认行为或者启用特定特性。下面是一个简单的例子展示如何声明一个 Bean 来管理 RedisTemplate 对象实例化过程中的序列化策略。 ```java 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.StringRedisTemplate; @Configuration public class RedisConfig { @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory){ return new StringRedisTemplate(connectionFactory); } } ``` 此代码片段展示了如何利用 Spring 提供的支持机制轻松实现对字符串键值对的操作能力提升效率的同时也增强了灵活性。 --- #### 编写服务逻辑 最后一步就是编写实际业务逻辑去调用 Redis 功能了。这里给出一段示范性的 Java 方法用于保存及检索用户登录状态记录至 Redis 缓存之中: ```java @Service public class LoginService { private final StringRedisTemplate template; public LoginService(StringRedisTemplate template) { this.template = template; } public void saveLoginStatus(String userId, boolean status) { template.opsForValue().set(userId, Boolean.toString(status)); } public Optional<Boolean> getLoginStatus(String userId) { String value = template.opsForValue().get(userId); if (value != null && !value.isEmpty()) { return Optional.of(Boolean.parseBoolean(value)); } else { return Optional.empty(); } } } ``` 这段示例演示了一个典型场景——即当某个用户的在线离线情况发生变化时更新其对应的标记位;而查询部分则负责读取当前已知的状态以便后续处理流程继续执行下去。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值