SpringBoot+Maven+MyBaitsPlus+MySQL+Redis——配置、开启Redis的基本使用

1、前置知识

(1)MybatisPlus操作数据库与代码生成:有道云笔记

2、安装RDIS监控软件:RedisDesktopManager

3、引入pom.xml引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>4.2.2</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
</dependency>

4、在config文件夹中创建RedisConfig,如下文件:

package MybatisPlusTest.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;


@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 选择redis作为默认缓存工具
     * @param redisConnectionFactory
     * @return
     */
    /*@Bean
    //springboot 1.xx
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        return rcm;
    }*/
    @Bean
//    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
//                .entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时
//        return RedisCacheManager
//                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
//                .cacheDefaults(redisCacheConfiguration).build();
//    }
    public RedisCacheManager redisCacheManager(LettuceConnectionFactory lettuceConnectionFactory){
        return RedisCacheManager.builder(lettuceConnectionFactory)
                .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig(Thread.currentThread().getContextClassLoader()))
                .build();
    }

    /**
     * retemplate相关配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }

    /**
     * 对hash类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * 对redis字符串类型数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * 对链表类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * 对无序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * 对有序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}

注意:

(1)如果爆红,先确定pom.xml引用依赖后,是否reload完成了。

(2)上面config文件的代码,可以暂时不用去了解每一个内容做什么,先配置完成。

5、Redis测试:

(1)在controller做注解,@Cacheable

(2)看是否正确存入到Redis缓存。正确存入Redis结果如下图:

注意:这里本人在使用时碰到了一个类转换的问题。根据下面这个博客内容debug通过:

spring boot 使用redis作为cache 出现:A cannot be cast to A.使用fastJson序列化 - 简书

6、关于注解@Cacheable的详细说明

其中:

(1)value:指明所返回的结果被存储与Redis的什么地方,文中代码对应如下图:

(2)key:这里指定为id,如果id都在redis当中有,则直接从缓存返回值,如果id不存在的话,则执行getuserById方法,从数据库获取。以上图为例:当id=1或2时,直接从缓存返回。其它则第一次从数据库取,其它批次从缓存取。

(3)condition:根据条件,判断结果是否存入缓存。如下图所示:

本文例子是将@Cacheable注解写在controller层,这仅为展示需要,真实项目开发过程中,应该放到service层,避免重复代码。网上有的说放到controller层更加灵活,其实完全没有必要,所有的数据都缓存,冗余一点个人感觉没什么关系。

本文完整代码:

有道云笔记

构建基于 Spring Boot + Maven + MyBatis + Redis + SQL 的后端项目是一个常见的选择,以下是详细的步骤和注意事项: --- ### **1. 创建 Spring Boot 项目** - 使用 [Spring Initializr](https://start.spring.io/) 或者 IDE 工具(如 IntelliJ IDEA)创建一个新的 Spring Boot 项目。 - 添加依赖项: - `spring-boot-starter-web`:支持 Web 应用开发。 - `spring-boot-starter-data-jpa`:用于 JPA 数据操作。 - `mybatis-spring-boot-starter`:集成 MyBatis 框架。 - `spring-boot-starter-redis`:集成 Redis 缓存功能。 - `mysql-connector-java` 或其他数据库驱动:连接 MySQL 等关系型数据库。 --- ### **2. 配置文件设置 (application.yml)** ```yaml server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC username: your_username password: your_password driver-class-name: com.mysql.cj.jdbc.Driver redis: host: localhost port: 6379 mybatis: mapper-locations: classpath:mapper/*.xml # 定义 Mapper 文件位置 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印 SQL 日志 ``` --- ### **3. 构建 Maven POM.xml** 确保添加必要的依赖库,例如: ```xml <dependencies> <!-- Spring Boot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- JSON Serialize & Deserialize --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> </dependencies> ``` --- ### **4. 设计数据层(MyBatis 和 SQL)** #### (1)Mapper 接口设计 编写对应的 Mapper 接口,并通过 XML 映射 SQL 查询语句。示例代码如下: ```java @Mapper public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User findById(int id); @Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})") int insertUser(User user); } ``` XML 文件路径应与配置一致 (`classpath:mapper/UserMapper.xml`)。 #### (2)实体类定义 根据表结构生成 Java 实体类: ```java @Data @AllArgsConstructor @NoArgsConstructor public class User { private Integer id; private String name; private Integer age; } ``` --- ### **5. 整合 Redis 缓存** Redis 可以作为缓存层优化性能。以下是如何将用户信息存储到 Redis 中的示例代码: ```java @Service public class UserService { @Autowired private StringRedisTemplate redisTemplate; public void cacheUser(String key, User user) { // 将对象转为 JSON 字符串保存至 Redis redisTemplate.opsForValue().set(key, new Gson().toJson(user)); } public Optional<User> getUserFromCache(String key) { String json = redisTemplate.opsForValue().get(key); return Objects.isNull(json) ? Optional.empty() : Optional.of(new Gson().fromJson(json, User.class)); } } ``` --- ### **6. 控制器部分** 提供 RESTful API 访问接口: ```java @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public ResponseEntity<?> getUserById(@PathVariable int id) { Optional<User> cachedResult = userService.getUserFromCache(String.valueOf(id)); if (!cachedResult.isPresent()) { // 如果未命中,则从数据库加载并更新缓存 System.out.println("Missed Cache! Fetching from DB..."); User dbResult = userRepository.findById(id); // 假设有一个 UserRepository 类 userService.cacheUser(String.valueOf(id), dbResult); return ResponseEntity.ok(dbResult); } else { System.out.println("Hit Cache!"); return ResponseEntity.ok(cachedResult.get()); } } } ``` --- ### **7. 测试运行** 启动应用程序并通过 Postman、Swagger UI 或浏览器测试 API 是否正常工作。 --- **总结提示**: 该架构适合中小型业务系统开发。如果需要更高扩展性和灵活性,可以考虑引入更多组件,比如消息队列 Kafka/RabbitMQ 或分布式事务解决方案 Seata/Dubbo。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值