当前位置: 首页 > news >正文

Spring Boot + MySQL + MyBatis(注解和XML配置两种方式)集成Redis的完整启用及配置详解,包含代码示例、注释说明和表格总结

以下是 Spring Boot + MySQL + MyBatis(注解和XML配置两种方式)集成Redis的完整启用及配置详解,包含代码示例、注释说明和表格总结:


1. 添加依赖

pom.xml中添加Spring Boot对MySQL、MyBatis和Redis的支持依赖:

<dependencies>
    <!-- Spring Boot核心 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- MySQL驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.30</version>
    </dependency>

    <!-- MyBatis集成 -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>3.0.1</version>
    </dependency>

    <!-- Redis和缓存 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>

    <!-- JSON序列化依赖 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
</dependencies>

2. 配置MySQL和Redis

application.properties中配置数据库和Redis信息:

# MySQL配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Redis配置
spring.redis.host=localhost
spring.redis.port=6379

# 缓存配置
spring.cache.type=redis
spring.cache.redis.key-prefix=myapp_
spring.cache.redis.time-to-live=3600000 # 全局缓存过期时间(1小时)

3. 数据库表结构(MySQL)

CREATE TABLE users (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    age INT
);

4. 实体类(User)

public class User {
    private Long id;
    private String name;
    private Integer age;

    // 构造函数、Getter/Setter省略
}

5. MyBatis Mapper配置(两种方式)

方式1:注解方式
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM users WHERE id = #{id}")
    User selectUserById(Long id);

    @Update("UPDATE users SET name=#{name}, age=#{age} WHERE id=#{id}")
    void updateUser(User user);

    @Delete("DELETE FROM users WHERE id=#{id}")
    void deleteUserById(Long id);
}
方式2:XML配置
  • 创建XML文件src/main/resources/mapper/UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
    <select id="selectUserById" resultType="User">
        SELECT * FROM users WHERE id = #{id}
    </select>

    <update id="updateUser">
        UPDATE users SET name=#{name}, age=#{age} WHERE id=#{id}
    </update>

    <delete id="deleteUserById">
        DELETE FROM users WHERE id=#{id}
    </delete>
</mapper>
  • 配置MyBatis扫描路径:在application.properties中添加:
    mybatis.mapper-locations=classpath:mapper/*.xml
    

6. 自定义Redis缓存配置

创建配置类以自定义Redis的序列化方式和缓存行为:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
public class RedisConfig {

    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        return RedisCacheConfiguration.defaultCacheConfig()
                // 键序列化器为String类型
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                // 值序列化器为JSON类型
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
                // 默认缓存过期时间(覆盖全局配置)
                .entryTtl(Duration.ofMinutes(30));
    }
}

7. Service层集成缓存

在Service层使用@Cacheable@CachePut等注解,结合MyBatis查询:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    // 1. 缓存查询用户的结果
    @Cacheable(value = "userCache", key = "#id")
    public User getUserById(Long id) {
        System.out.println("从数据库查询用户ID:" + id);
        return userMapper.selectUserById(id);
    }

    // 2. 更新用户信息并更新缓存
    @CachePut(value = "userCache", key = "#user.id")
    public User updateUser(User user) {
        System.out.println("更新用户缓存:" + user.getId());
        userMapper.updateUser(user);
        return user;
    }

    // 3. 删除指定用户的缓存
    @CacheEvict(value = "userCache", key = "#id")
    public void deleteUserById(Long id) {
        System.out.println("删除用户缓存:" + id);
        userMapper.deleteUserById(id);
    }
}

8. Controller层示例

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @PutMapping("/update")
    public User updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUserById(id);
    }
}

9. 关键配置与注解总结

模块配置/注解作用示例
依赖mybatis-spring-boot-starter集成MyBatis与Spring Bootpom.xml添加依赖
数据库配置spring.datasource.*配置MySQL连接信息spring.datasource.url=jdbc:mysql://...
Redis配置spring.redis.*配置Redis服务器地址和端口spring.redis.host=localhost
MyBatis注解方式@Mapper标识MyBatis接口映射@Mapper
MyBatis XML方式mybatis.mapper-locations指定XML映射文件路径classpath:mapper/*.xml
缓存管理@EnableCaching启用Spring缓存注解支持主类添加注解
缓存注解@Cacheable缓存方法返回结果,避免重复数据库查询@Cacheable(value = "userCache", key = "#id")
更新缓存@CachePut更新缓存而不影响方法执行(如更新用户信息)@CachePut(value = "userCache", key = "#user.id")
清除缓存@CacheEvict删除指定缓存或全部缓存(如删除用户后清除对应缓存)@CacheEvict(value = "userCache", key = "#id")

10. 注意事项

  1. Mapper配置

    • 注解方式:需在启动类或配置类上添加@MapperScan("com.example.mapper")指定包路径。
    • XML方式:需在application.properties中配置mybatis.mapper-locations
  2. 序列化

    • 默认使用JdkSerializationRedisSerializer,若需JSON序列化需自定义配置(如GenericJackson2JsonRedisSerializer)。
  3. 缓存键设计

    • 确保缓存键唯一且可读,如使用#id动态生成键。
    • 可通过keyGenerator自定义键生成逻辑。
  4. 事务管理

    • 对于数据库操作,需结合@Transactional注解确保数据一致性。

通过以上步骤,可实现Spring Boot + MySQL + MyBatis(注解或XML配置)与Redis的高效集成,利用缓存减少数据库压力,提升系统性能。


文章转载自:
http://abnaki.wanhuigw.com
http://bacteria.wanhuigw.com
http://awed.wanhuigw.com
http://caaba.wanhuigw.com
http://approx.wanhuigw.com
http://capri.wanhuigw.com
http://auspice.wanhuigw.com
http://cancered.wanhuigw.com
http://bardling.wanhuigw.com
http://ameloblast.wanhuigw.com
http://apocrypha.wanhuigw.com
http://bravo.wanhuigw.com
http://appellation.wanhuigw.com
http://ashiver.wanhuigw.com
http://archaeologize.wanhuigw.com
http://autarky.wanhuigw.com
http://bifoliate.wanhuigw.com
http://bigarade.wanhuigw.com
http://autopotamic.wanhuigw.com
http://adeodatus.wanhuigw.com
http://bloodshot.wanhuigw.com
http://amex.wanhuigw.com
http://activable.wanhuigw.com
http://breathalyser.wanhuigw.com
http://astrocyte.wanhuigw.com
http://adjudgement.wanhuigw.com
http://bari.wanhuigw.com
http://battlefront.wanhuigw.com
http://carbohydrate.wanhuigw.com
http://audit.wanhuigw.com
http://www.dtcms.com/a/110257.html

相关文章:

  • AI设计再现新引擎,科技创新又添新动能——广东省首家行业AI设计工程中心获批成立
  • 力扣刷题——2331.计算布尔二叉树的值
  • 【AI视频】度加视频测试
  • HTML jQuery PDF Annotation plugin library free online API examples
  • 蓝桥杯常用算法介绍:动态规划(DP)
  • 自动驾驶中的实时挑战:如何优化车辆动力学模型
  • YOLO系列论文图表绘制代码
  • BFC特性,开启BFC的方法,怪异盒子模型
  • 如何用 Three.js 和 Vue 3 实现 3D 商品展示
  • Java面试黄金宝典31
  • C语言--统计字符串中最长的单词
  • [leetcode]queue的操作的回顾
  • 【CMOS输出缓冲器驱动强度】
  • 系统架构设计理论之架构风格与模式(分层、MVC、微服务、事件驱动)
  • Android URL中+转义之后导致服务器请求无法获得正确的参数值
  • LeetCode算法题(Go语言实现)_28
  • 【电平转换原理】
  • WinDbg. From A to Z! 笔记(下)
  • 大坑!GaussDB数据库批量插入数据变只读
  • ctfshow _萌新 萌新_密码篇
  • 常见集合篇(五)深入解析 HashMap:从原理到源码,全方位解读
  • 青铜与信隼的史诗——TCP与UDP的千年博弈
  • 【JavaScript】闭包小练习(数字范围起始值和结束值)
  • RHCSA Linux 系统创建文件
  • Vim操作指令全解析
  • 质检LIMS实验室系统在环保技术企业的应用 环保技术研发场景的特殊性需求
  • C++高效读取大规模文本格式点云(windows)
  • 手机归属地查询Api接口,数据准确可靠
  • 根据时间范围得出雪花算法(snowflake)ID的工具类-基于时间反推ID范围
  • AiCube 试用 - 创建流水灯工程