SpringBoot 2+JPA+Redisキャッシュ

9472 ワード

pomファイル


  4.0.0
  
    bsea
    springboot2
    0.0.1-SNAPSHOT
  
  springbootJPARedis
  
	
	 
          
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
		
			org.springframework.boot
			spring-boot-starter-web
		
		
		
        
        
		 
		    mysql
		    mysql-connector-java
		    
		    
		
		
		
			org.springframework.boot
			spring-boot-starter-data-jpa
		
		
       
        
        
         
            com.alibaba
            fastjson
            1.2.38
        
	
	


クラスの開始

package com.xsz;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching
@SpringBootApplication
public class App {
	
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

}


プロファイル

package com.xsz.config;


import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
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.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

	//      key    
	@Bean
	public KeyGenerator keyGenerator() {
		return new KeyGenerator() {
			@Override
			public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
				StringBuffer sb = new StringBuffer();
				sb.append(target.getClass().getName());
				sb.append(method.getName());
				for (Object obj : params) {
					sb.append(obj.toString());
				}
				return sb.toString();
			}
		};
	}

	//      
	@Bean
	public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
		RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
				.entryTtl(Duration.ofHours(1)); //           
		return RedisCacheManager
				.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
				.cacheDefaults(redisCacheConfiguration).build();
	}

	@Bean
	@SuppressWarnings({"rawtypes", "unchecked"})
	public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory){
		RedisTemplate redisTemplate=new RedisTemplate<>();
		redisTemplate.setConnectionFactory(connectionFactory);
		//  Jackson2JsonRedisSerializer          
		Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
		ObjectMapper objectMapper=new ObjectMapper();
		objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
		objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer.setObjectMapper(objectMapper);


		//  value      
		redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
		//  key      
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}

//	private void setSerializer(StringRedisTemplate template) {
//		@SuppressWarnings({ "rawtypes", "unchecked" })
//		Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//		ObjectMapper om = new ObjectMapper();
//		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//		om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//		jackson2JsonRedisSerializer.setObjectMapper(om);
//		template.setValueSerializer(jackson2JsonRedisSerializer);
//	}
}





Service

package com.xsz.service;

import javax.annotation.Resource;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.xsz.entity.Blog;
import com.xsz.repository.BlogRepository;
import com.xsz.repository.UserRepository;
@CacheConfig(cacheNames = "blogService")
@Service
public class BlogService {
	@Resource
	BlogRepository blogRepository;

	@Cacheable(key = "#p0")
    public Blog selectByPrimaryKey(String id) {
        return blogRepository.findById(id).get();
    }
	
	@CachePut(key = "#p0.id")
    public Blog updateBy(Blog blog) {
        return blogRepository.save(blog);
    }
}


/**
*
* 1              
*        Spring             Spring Cache。      @Cacheable @CacheEvict。
*          @Cacheable         Spring Cache        ,   @CacheEvict                   Spring Cache      。
*                    Spring     Cache           。
*
* 1.1    @Cacheable
*        @Cacheable          ,          。                     ,
*                                  。           ,Spring                ,
*                                       ,           。Spring                    ,
*                  ,     ,Spring       ,          ,         。
*                                           。@Cacheable        ,value、key condition。
*
* 1.1.1  value    Cache  
*        value        ,                   Cache  ,  Cache   。      Cache      Cache,       Cache       。
*
*    @Cacheable("cache1")//Cache    cache1  
*
*    public User find(Integer id) {
*
*       returnnull;
*
*    }
*
*
*
*    @Cacheable({"cache1", "cache2"})//Cache    cache1 cache2  
*
*    public User find(Integer id) {
*
*       returnnull;
*
*    }
*
*
*
* 1.1.2    key     key
*        key       Spring             key 。
*             SpringEL   。           ,
*        Spring         key。
*                     ,
*                      。
*
*                     Spring EL         key。
*           EL                   。
*                       “#   ”  “#p  index”。
*                   key   。
*
*    @Cacheable(value="users", key="#id")
*
*    public User find(Integer id) {
*
*       returnnull;
*
*    }
*
*
*
*    @Cacheable(value="users", key="#p0")
*
*    public User find(Integer id) {
*
*       returnnull;
*
*    }
*
*
*
*    @Cacheable(value="users", key="#user.id")
*
*    public User find(User user) {
*
*       returnnull;
*
*    }
*    1.2     @CachePut
*           Spring Cache    ,    @Cacheable     ,Spring          Cache       key     ,            ,                ,                    。@CachePut               。 @Cacheable      @CachePut                             ,           ,                     。
*
*        @CachePut            。  @CachePut           @Cacheable    。
*
*    @CachePut("users")//        ,            
*
*    public User find(Integer id) {
*
*       returnnull;
*
*    }
*
*
*
* 1.3     @CacheEvict
*        @CacheEvict                     。                                。@CacheEvict        value、key、condition、allEntries beforeInvocation。  value、key condition    @Cacheable       。 value            Cache  (  Cache   );key          key,               key;condition           。                 allEntries beforeInvocation。
*
* 1.3.1  allEntries  
*        allEntries boolean  ,                。   false,     。    allEntries true ,Spring Cache      key。        Cache         ,              。
*
*    @CacheEvict(value="users", allEntries=true)
*
*    public void delete(Integer id) {
*
*       System.out.println("delete user by id: " + id);
*
*    }
*
*
*
*
*/