1 dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2 application.properties
#Redis服务连接配置
#Redis服务地址
spring.redis.host=127.0.0.1
#Redis服务器连接端口
spring.redis.port=6379
#Redis服务器连接密码
spring.redis.password=
3 repository
public interface CommentRepository extends JpaRepository<Comment, Integer> {
//根据评论id修改评论作者
@Transactional
@Modifying
@Query(value = "update t_comment c set c.author = ?1 where c.id=?2", nativeQuery = true)
public int updateComment(String author, Integer id);
}
4 service
@Cacheable @CachePut @CacheEvict
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;
import java.util.Optional;
@Service
public class CommentService {
@Autowired
private CommentRepository commentRepository;
//@Cacheable: 将该方法查询结果comment存放在springboot默认缓存中
//cacheNames: 起一个缓存命名空间 对应缓存唯一标识
// value: 缓存结果 key:默认在只有一个参数的情况下,key值默认就是方法参数值 如果没有参数或者多个参数的情况:simpleKeyGenerate
// 查询方法
@Cacheable(cacheNames = "comment", unless = "#result==null")
public Comment findCommentById(Integer id) {
Optional<Comment> byId = commentRepository.findById(id);
if (byId.isPresent()) {
Comment comment = byId.get();
return comment;
}
return null;
}
//更新方法
@CachePut(cacheNames = "comment", key = "#result.id")
public Comment updateComment(Comment comment) {
commentRepository.updateComment(comment.getAuthor(), comment.getId());
return comment;
}
//删除方法
@CacheEvict(cacheNames = "comment")
public void deleteComment(Integer id) {
commentRepository.deleteById(id);
}
}
5 controller
@RestController
public class CommentController {
@Autowired
private CommentService commentService;
@RequestMapping("/findCommentById")
public Comment findCommentById(Integer id) {
Comment comment = commentService.findCommentById(id);
return comment;
}
@RequestMapping("/updateComment")
public Comment updateComment(Comment comment) {
Comment commentById = commentService.findCommentById(comment.getId());
commentById.setAuthor(comment.getAuthor());
Comment comment1 = commentService.updateComment(commentById);
return comment1;
}
@RequestMapping("/deleteComment")
public void deleteComment(Integer id) {
commentService.deleteComment(id);
}
}
6 缓存对象序列化
@Entity
@Table(name = "t_comment")
public class Comment implements Serializable {
7 序列化 方式 指定 Configuration
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
public class RedisConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// 分别创建String和JSON格式序列化对象,对缓存数据key和value进行转换
RedisSerializer<String> strSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jacksonSeial =
new Jackson2JsonRedisSerializer(Object.class);
// 解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
// 定制缓存数据序列化方式及时效
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofDays(1))
.serializeKeysWith(RedisSerializationContext.SerializationPair
.fromSerializer(strSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(jacksonSeial))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager
.builder(redisConnectionFactory).cacheDefaults(config).build();
return cacheManager;
}
}
一会儿结果是这样的
127.0.0.1:6379> get comment::3
["com.lagou.pojo.Comment",{"id":3,"content":"大风车","author":"mike","aId":1}]
8 启动类
@EnableCaching // 开启spring boot基于注解的缓存管理支持
@SpringBootApplication
public class SpringbootDemoCacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoCacheApplication.class, args);
}
}
9 测试
http://127.0.0.1:8080/findCommentById?id=1
点多次
Hibernate: select comment0_.id as id1_0_0_, comment0_.a_id as a_id2_0_0_, comment0_.author as author3_0_0_, comment0_
10 更新测试
http://localhost:8080/updateComment?id=1&author=abcd
然后
http://127.0.0.1:8080/findCommentById?id=1
Hibernate: update t_comment c set c.author = ? where c.id=?
11 删除测试
http://localhost:8080/deleteComment?id=1
缓存 数据库均被删除
Hibernate: delete from t_comment where id=?
12 redis 有效期设置
spring.cache.redis.time-to-live=60000