以下是 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 Boot | pom.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. 注意事项
-
Mapper配置:
- 注解方式:需在启动类或配置类上添加
@MapperScan("com.example.mapper")
指定包路径。 - XML方式:需在
application.properties
中配置mybatis.mapper-locations
。
- 注解方式:需在启动类或配置类上添加
-
序列化:
- 默认使用
JdkSerializationRedisSerializer
,若需JSON序列化需自定义配置(如GenericJackson2JsonRedisSerializer
)。
- 默认使用
-
缓存键设计:
- 确保缓存键唯一且可读,如使用
#id
动态生成键。 - 可通过
keyGenerator
自定义键生成逻辑。
- 确保缓存键唯一且可读,如使用
-
事务管理:
- 对于数据库操作,需结合
@Transactional
注解确保数据一致性。
- 对于数据库操作,需结合
通过以上步骤,可实现Spring Boot + MySQL + MyBatis(注解或XML配置)与Redis的高效集成,利用缓存减少数据库压力,提升系统性能。