org.springframework.boot spring-boot-starter-data-redis
# Redis 服务器地址spring.redis.host = 127.0.0.1# Redis 服务器连接端口spring.redis.port = 6379# Redis 服务器连接密码 ( 默认为空 )spring.redis.password =
spring: # MySQL数据库连接配置 datasource: url: jdbc:mysql://localhost:3306/springbootdata?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC username: root password: 123 jpa: # 显示使用JPA进行数据库查询的SQL语句 show-sql: true redis: host: 192.168.48.67 port: 6379 password:
@EnableCaching//开启了SpringBoot基于注解的缓存管理实现
下面我们针对@Cacheable注解的属性进行具体讲解。
package com.example.demo.service.imp;
import com.example.demo.domain.Comment;
import com.example.demo.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.sql.Time;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@Service
public class CommentService {
@Autowired
private CommentRepository commentRepository;
@Autowired
private RedisTemplate redisTemplate;
public Comment findById(int comment_id) {
//通过RedisTemplate查询缓存中的数据(Redis中的数据)
Object object = redisTemplate.opsForValue().get("comment_" + comment_id);
if (object !=null){
return (Comment) object;
} else {
Optional optional = commentRepository.findById(comment_id);
Comment comment = new Comment();
if (optional.isPresent()) {
comment = optional.get();
}
redisTemplate.opsForValue().set("comment_"+comment_id,comment,1,TimeUnit.DAYS);
return comment;
}
}
public Comment updateComment(Comment comment) {
commentRepository.updateComment(comment.getAuthor(),
comment.getArticleId());
redisTemplate.opsForValue().set("comment_"+comment.getId(),comment);
return comment;
}
public void deleteComment(int comment_id) {
commentRepository.deleteById(comment_id);
redisTemplate.delete("comment_"+comment_id);
}
}
package com.example.demo.config;
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 {
//Api开发
@Bean
public RedisTemplate