springboot整合redis整合@Cacheable、@CachePut、@CacheEvict注解增删改查实例
时间: 2023-08-16 20:08:50 浏览: 67
好的,下面是一个使用Spring Boot整合Redis的`@Cacheable`、`@CachePut`、`@CacheEvict`注解实现增删改查的示例:
1. 添加Redis依赖
在pom.xml中添加以下依赖:
```xml
<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>
```
2. 配置Redis连接
在application.properties中添加以下配置:
```properties
# Redis连接配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
# 开启缓存
spring.cache.type=redis
```
3. 编写Redis配置类
```java
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
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.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.reflect.Method;
import java.util.Arrays;
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// key序列化方式
RedisSerializer<String> stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer); // key
redisTemplate.setHashKeySerializer(stringRedisSerializer); // hash key
// value序列化方式
RedisSerializer<Object> valueRedisSerializer = new GenericJackson2JsonRedisSerializer();
redisTemplate.setValueSerializer(valueRedisSerializer); // value
redisTemplate.setHashValueSerializer(valueRedisSerializer); // hash value
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory);
return builder.build();
}
@Bean
public KeyGenerator wiselyKeyGenerator() {
return (Object target, Method method, Object... params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
Arrays.stream(params).forEach(param -> sb.append(param.toString()));
return sb.toString();
};
}
}
```
4. 编写实体类
```java
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Integer age;
public User(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
```
5. 编写Service
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserDao userDao;
@Cacheable(value = "user", keyGenerator = "wiselyKeyGenerator")
public User getUserById(Integer id) {
return userDao.getUserById(id);
}
@CachePut(value = "user", keyGenerator = "wiselyKeyGenerator")
public User updateUser(User user) {
userDao.updateUser(user);
return user;
}
@CacheEvict(value = "user", keyGenerator = "wiselyKeyGenerator")
public void deleteUserById(Integer id) {
userDao.deleteUserById(id);
}
}
```
6. 编写Controller
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUserById(@PathVariable Integer id) {
return userService.getUserById(id);
}
@PutMapping("")
public User updateUser(@RequestBody User user) {
return userService.updateUser(user);
}
@DeleteMapping("/{id}")
public void deleteUserById(@PathVariable Integer id) {
userService.deleteUserById(id);
}
}
```
7. 测试
启动应用后,可以通过以下方式测试:
- 获取用户:GET http://localhost:8080/user/1
- 更新用户:PUT http://localhost:8080/user
请求体:
```json
{
"id": 1,
"name": "Tom",
"age": 20
}
```
- 删除用户:DELETE http://localhost:8080/user/1
以上就是一个使用Spring Boot整合Redis的`@Cacheable`、`@CachePut`、`@CacheEvict`注解实现增删改查的示例。