赞
踩
import javax . persistence . * ;@Entity ( name = "t_comment" ) // 设置 ORM 实体类,并指定映射的表名public class Comment {@Id // 表明映射对应的主键 id@GeneratedValue ( strategy = GenerationType . IDENTITY ) // 设置主键自增策略private Integer id ;private String content ;private String author ;@Column ( name = "a_id" ) // 指定映射的表字段名private Integer aId ;// 省略属性 getXX() 和 setXX() 方法// 省略 toString() 方法}
public interface CommentRepository extends JpaRepository < Comment , Integer > {// 根据评论 id 修改评论作者 author@Transactional@Modifying@Query ( "update t_comment c set c.author = ?1 where c.id=?2" )public int updateComment ( String author , Integer id );}
@Servicepublic class CommentService {@Autowiredprivate CommentRepository commentRepository ;public Comment findCommentById ( Integer id ){Optional < Comment > comment = commentRepository . findById ( id );if ( comment . isPresent ()){Comment comment1 = comment . get ();return comment1 ;}return null ;}
@RestControllerpublic class CommentController {@Autowiredprivate CommentService commentService ;@RequestMapping ( value = "/findCommentById" )public Comment findCommentById ( Integer id ){Comment comment = commentService . findCommentById ( id );return comment ;}}
# MySQL 数据库连接配置spring.datasource.url = jdbc : mysql : //localhost : 3306/springbootdata?serverTimezone = UTCspring.datasource.username = rootspring.datasource.password = root# 显示使用 JPA 进行数据库查询的 SQL 语句spring.jpa.show-sql = true# 开启驼峰命名匹配映射mybatis.configuration.map-underscore-to-camel-case = true# 解决乱码spring.http.encoding.force-response = true
@EnableCaching // 开启 Spring Boot 基于注解的缓存管理支持@SpringBootApplicationpublic class Springboot04CacheApplication {public static void main ( String [] args ) {SpringApplication . run ( Springboot04CacheApplication . class , args );}}
/ 根据评论 id 查询评论信息@Cacheable ( cacheNames = "comment" )public Comment findById ( int comment_id ){Optional < Comment > optional = commentRepository . findCommentById ( comment_id );if ( optional . isPresent ()){return optional . get ();}return null ;}
<dependency><groupId> org.springframework.boot </groupId><artifactId> spring-boot-starter-data-redis </artifactId></dependency>
# Redis 服务地址spring.redis.host = 127.0.0.1# Redis 服务器连接端口spring.redis.port = 6379# Redis 服务器连接密码(默认为空)spring.redis.password =
@Servicepublic class CommentService {@Autowiredprivate CommentRepository commentRepository ;@Cacheable ( cacheNames = "comment" , unless = "#result==null" )public Comment findCommentById ( Integer id ){Optional < Comment > comment = commentRepository . findById ( id );if ( comment . isPresent ()){Comment comment1 = comment . get ();return comment1 ;}return null ;}@CachePut ( cacheNames = "comment" , key = "#result.id" )public Comment updateComment ( Comment comment ) {commentRepository . updateComment ( comment . getAuthor (), comment . getaId ());return comment ;}@CacheEvict ( cacheNames = "comment" )public void deleteComment ( int comment_id ) {commentRepository . deleteById ( comment_id );}}
# 对基于注解的 Redis 缓存数据统一设置有效期为 1 分钟,单位毫秒spring.cache.redis.time-to-live = 60000
@Servicepublic class ApiCommentService {@Autowiredprivate CommentRepository commentRepository ;@Autowiredprivate RedisTemplate redisTemplate ;public Comment findCommentById ( Integer id ){Object o = redisTemplate . opsForValue (). get ( "comment_" + id );if ( o != null ){return ( Comment ) o ;} else {// 缓存中没有,从数据库查询Optional < Comment > byId = commentRepository . findById ( id );if ( byId . isPresent ()){Comment comment = byId . get ();// 将查询结果存入到缓存中,并设置有效期为 1 天redisTemplate . opsForValue (). set ( "comment_" + id , comment , 1 , TimeUnit . DAYS );return comment ;} else {return null ;}}}public Comment updateComment ( Comment comment ) {commentRepository . updateComment ( comment . getAuthor (), comment . getaId ());// 更新数据后进行缓存更新redisTemplate . opsForValue (). set ( "comment_" + comment . getId (), comment );return comment ;}public void deleteComment ( int comment_id ) {commentRepository . deleteById ( comment_id );redisTemplate . delete ( "comment_" + comment_id );}
@RestController@RequestMapping ( "api" ) // 窄化请求路径public class ApiCommentController {@Autowiredprivate ApiCommentService commentService ;@RequestMapping ( value = "/findCommentById" )public Comment findCommentById ( Integer id ){Comment comment = commentService . findCommentById ( id );return comment ;}@RequestMapping ( value = "/updateComment" )public void updateComment ( Comment comment ){Comment comment2 = commentService . findCommentById ( comment . getId ());comment . setAuthor ( comment . getAuthor ());commentService . updateComment ( comment );}@RequestMapping ( value = "/deleteComment" )public void deleteComment ( int id ){commentService . deleteComment ( id );}}
public class RedisTemplate < K , V > extends RedisAccessorimplements RedisOperations < K , V > ,BeanClassLoaderAware {// 声明了 key 、 value 的各种序列化方式,初始值为空@Nullableprivate RedisSerializer keySerializer = null ;@Nullableprivate RedisSerializer valueSerializer = null ;@Nullableprivate RedisSerializer hashKeySerializer = null ;@Nullableprivate RedisSerializer hashValueSerializer = null ;...// 进行默认序列化方式设置,设置为 JDK 序列化方式public void afterPropertiesSet () {super . afterPropertiesSet ();boolean defaultUsed = false ;if ( this . defaultSerializer == null ) {this . defaultSerializer = new JdkSerializationRedisSerializer (this . classLoader != null ?this . classLoader : this . getClass (). getClassLoader ());}...}...}
public class RedisAutoConfiguration {@Bean@ConditionalOnMissingBean (name = { "redisTemplate" })public RedisTemplate < Object , Object > redisTemplate ( RedisConnectionFactoryredisConnectionFactory ) throwsUnknownHostException {RedisTemplate < Object , Object > template = new RedisTemplate ();template . setConnectionFactory ( redisConnectionFactory );return template ;}...}
@Configurationpublic class RedisConfig {@Beanpublic RedisTemplate < Object , Object > redisTemplate ( RedisConnectionFactoryredisConnectionFactory ) {RedisTemplate < Object , Object > template = new RedisTemplate ();template . setConnectionFactory ( redisConnectionFactory );// 使用 JSON 格式序列化对象,对缓存数据 key 和 value 进行转换Jackson2JsonRedisSerializer jacksonSeial = newJackson2JsonRedisSerializer ( Object . class );// 解决查询缓存转换异常的问题ObjectMapper om = new ObjectMapper ();om . setVisibility ( PropertyAccessor . ALL , JsonAutoDetect . Visibility . ANY );om . enableDefaultTyping ( ObjectMapper . DefaultTyping . NON_FINAL );jacksonSeial . setObjectMapper ( om );// 设置 RedisTemplate 模板 API 的序列化方式为 JSONtemplate . setDefaultSerializer ( jacksonSeial );return template ;}}
@Configurationclass RedisCacheConfiguration {@Beanpublic RedisCacheManager cacheManager ( RedisConnectionFactoryredisConnectionFactory , ResourceLoaderresourceLoader ) {RedisCacheManagerBuilder builder =RedisCacheManager . builder ( redisConnectionFactory ). cacheDefaults ( this . determineConfiguration ( resourceLoader . getClassLoader ()));List < String > cacheNames = this . cacheProperties . getCacheNames ();if ( ! cacheNames . isEmpty ()) {builder . initialCacheNames ( new LinkedHashSet ( cacheNames ));}return( RedisCacheManager ) this . customizerInvoker . customize ( builder . build ());}private org . springframework . data . redis . cache . RedisCacheConfigurationdetermineConfiguration ( ClassLoader classLoader ){if ( this . redisCacheConfiguration != null ) {return this . redisCacheConfiguration ;} else {Redis redisProperties = this . cacheProperties . getRedis ();org . springframework . data . redis . cache . RedisCacheConfiguration config=org . springframework . data . redis . cache . RedisCacheConfiguration . defaultCacheConfig();config =config . serializeValuesWith ( SerializationPair . fromSerializer (newJdkSerializationRedisSerializer ( classLoader )));...return config ;}}}
@Beanpublic RedisCacheManager cacheManager ( RedisConnectionFactoryredisConnectionFactory ) {// 分别创建 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 ;}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。