Redis之Spring boot集成redis和Spring cache

@SpringBootApplication
@EnableCaching
public class Redis3Application {
    public static void main(String[] args) {
        SpringApplication.run(Redis3Application.class, args);
    }
}
 
 
@Configuration
public class MyRedisConfig {
 
    @Bean(name = "redisTemplate")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(keySerializer());
        redisTemplate.setHashKeySerializer(keySerializer());
        redisTemplate.setValueSerializer(valueSerializer());
        redisTemplate.setHashValueSerializer(valueSerializer());
        return redisTemplate;
    }
 
    @Primary
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){
        //缓存配置对象
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L)) //设置缓存的默认超时时间:30分钟
                .disableCachingNullValues()             //如果是空值,不缓存
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))         //设置key序列化器
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer())));  //设置value序列化器
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }
    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }
    private RedisSerializer<Object> valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }
}
 
 
 
@Data
public class Product {
    String name;
    int id;
    double print;
    String factoryname;
}
 
 
 
@RestController
public class ProductController {
 
    @Autowired
    private ProductService productService;
 
    @GetMapping("/product/{id}")
    public Product getProduct(@PathVariable("id") Long id) {
 
        Product product = productService.getProductById(id);
        return product;
    }
 
    //prooduct?productid=1&productName= &
    @GetMapping("/product")
    public Product updateProduct(Product product) {
        productService.updateProduct(product);
        return product;
    }
 
    @GetMapping("/delproduct")
    public String delProduct(@RequestParam(value="id") Long id) {
 
        productService.deleteProductById(id);
        return "ok";
    }
 
    @GetMapping("/product/name/{productName}")
    public Product getEmpByLastName(@PathVariable("productName") String productName){
        return productService.getProductByName(productName);
    }
}
 
 
 
@Service
@CacheConfig(cacheNames = "product")
public class ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Cacheable(cacheNames = "product1",key = "#root.methodName+'['+#id+']'")
    //@Cacheable(cacheNames = {"product1","product2"})// 默认key为参数,多个参数SimpleKey [arg1,arg2]
    //@Cacheable(cacheNames = "product",key = "#root.methodName+'['+#id+']'")
    //@Cacheable(cacheNames = "product",keyGenerator = "myKeyGenerator")
    //@Cacheable(cacheNames = "product",key = "#root.methodName+'['+#id+']'",condition="#a0>10",unless = "#a0==11") //或者condition="#id>10")
    public Product getProductById(Long id){
        Product product =productMapper.getProductById(id);
        System.out.println(product);
        return product;
    }

    @CachePut(value="product",key = "#result.id",condition = "#result!=null")
    public  Product updateProduct(Product product){
        int count = productMapper.updateProduct(product);
        System.out.println("影响行数:"+count);
        if(count>0){
            return product;
        }else{
            return null;
        }
    }

    //@CacheEvict(value="product",key="#id")
    //@CacheEvict(value="product",allEntries = true) //清除所有缓存
    @CacheEvict(value="product",allEntries = true,beforeInvocation = true) //清除所有缓存
    public boolean deleteProductById(Long id) {
        productMapper.deleteProductById(id);
        return true;
    }

    //含有CachePut注解,所以执行这个方法时一定会查询数据库,及时有cacheable注解
    @Caching(
            cacheable = {@Cacheable(value="product",key="#productName")},
            put = {
                    @CachePut(value="product",key="#result.id"),
                    @CachePut(value="product",key="#result.name")
            }
    )
    public  Product getProductByName(String productName){

        Product product =productMapper.getProductByName(productName);

        return product;
    }
}



@Service
public class ProductMapper {
    private static Product product;
    static {
        product = new Product();
        product.setFactoryname("工厂名字1");
        product.setName("产品1");
        product.setId(1);
        product.setPrint(20);
    }
    public Product getProductById(Long id){
        System.out.println("执行方法:"+ "getProductById");
        return product;
    }
    public int updateProduct(Product product){
        System.out.println("执行方法:"+ "updateProduct");
        this.product  = product;
        product.setName(product.getName()+" 修改 ");
        return 1;
    }
     void deleteProductById(Long id){
         System.out.println("执行方法:"+ "deleteProductById");
         product = null;
    }
    Product getProductByName(String productName){
        System.out.println("执行方法:"+ "getProductByName");
        return product;
    }
}

 

posted @ 2020-08-19 09:13  yaohuiqin  阅读(131)  评论(0编辑  收藏  举报