SpringBoot使用Redis做缓存,@Cacheable、@CachePut、@CacheEvict等注解的使用

SpringBoot使用Redis做缓存,@Cacheable、@CachePut、@CacheEvict等注解的使用

导入依赖
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
配置文件
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.142.142
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
配置Redis的class文件
package com.frog.mvcdemo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.lang.reflect.Method;

@CacheConfig
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{

    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            //为给定的方法及其参数生成一个键
            //格式为:com.frog.mvcdemo.controller.FrogTestController-show-[params]
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuffer sb = new StringBuffer();
                sb.append(target.getClass().getName());//类名
                sb.append("-");
                sb.append(method.getName());//方法名
                sb.append("-");
                for (Object param: params ) {
                    sb.append(param.toString());//参数
                }
                return sb.toString();
            }
        };
    }

    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //设置默认的过期时间(以秒为单位)
        rcm.setDefaultExpiration(600);
        //rcm.setExpires();设置缓存区域(按key)的过期时间(以秒为单位)
        return rcm;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        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);
        template.afterPropertiesSet();
        return template;
    }
}
缓存注解的使用

@Cacheable
Spring 在执行 @Cacheable 标注的方法前先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,执行该方法并将方法返回值放进缓存。
参数: value缓存名、 key缓存键值、 condition满足缓存条件、unless否决缓存条件

@CachePut
和 @Cacheable 类似,但会把方法的返回值放入缓存中, 主要用于数据新增和修改方法

@CacheEvict
方法执行成功后会从缓存中移除相应数据。
参数: value缓存名、 key缓存键值、 condition满足缓存条件、 unless否决缓存条件、 allEntries是否移除所有数据(设置为true时会移除所有缓存)

参考链接:
http://rensanning.iteye.com/blog/2362184
http://blog.csdn.net/whatlookingfor/article/details/51833378

注解使用
package com.frog.mvcdemo.controller;

import com.frog.mvcdemo.entity.Frog;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@CacheConfig(cacheNames = "frogtest")
@RestController
@RequestMapping(value = "/frogtest")
public class FrogTestController {

    @Cacheable()
    @ApiOperation(value = "获取Frog的列表")
    @RequestMapping(value = "",method = RequestMethod.GET)
    public List<Frog> show(){
        List<Frog> list = new ArrayList<>();
        list.add(new Frog(1,"one",2,new Date(),"controllertest"));
        list.add(new Frog(2,"two",3,new Date(),"controllertest"));
        return list;
    }

    @Cacheable()
    @ApiOperation(value = "获取Frog详细信息",notes = "根据id查询对应Frog信息")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "int", paramType = "path")
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Map<String,Object> showById(@PathVariable int id){
        Map<String,Object> map = new HashMap<>();
        if(id == 1){
            map.put("FROG",new Frog(1,"one",3,new Date(),"showById"));
            map.put("RESULT","SUCCESS");
        }else{
            map.put("FROG",null);
            map.put("RESULT","ERROR");
        }
        return map;
    }

    @CacheEvict(allEntries = true)
    @ApiOperation(value = "添加Frog详细信息",notes = "添加一条Frog的详细信息")
    @ApiImplicitParam(name = "frog", value = "Frog实体", required = true, dataType = "Frog")
    @RequestMapping(value = "",method = RequestMethod.POST)
    public Map<String,Object> add(@RequestBody Frog frog){
        Map<String,Object> map = new HashMap<>();
        map.put("FROG",frog);
        map.put("RESULT","SUCCESS");
        return map;
    }

    @CacheEvict(allEntries = true)
    @ApiOperation(value = "删除Frog详细信息",notes = "根据id删除对应Frog的详细信息")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "int", paramType = "path")
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public Map<String,Object> deleteById(@PathVariable int id){
        Map<String,Object> map = new HashMap<>();
        if(id != 0){
            map.put("FROG",new Frog(id,"testfrog",id,new Date(),"deleteById"));
            map.put("RESULT","SUCCESS");
        }else{
            map.put("FROG",null);
            map.put("RESULT","ERROR");
        }
        return map;
    }

    @CacheEvict(allEntries = true)
    @ApiOperation(value = "更新Frog详细信息",notes = "根据id更新Frog的详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "int",paramType = "path"),
            @ApiImplicitParam(name = "frog", value = "Frog实体", required = true, dataType = "Frog")
    })
    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    public Map<String,Object> updateById(@PathVariable int id,@RequestBody Frog frog){
        Map<String,Object> map = new HashMap<>();
            map.put("FROG",frog);
            map.put("RESULT","SUCCESS");
            map.put("ID",id);
        return map;
    }
}

缓存一般加在dao层或service层,发生回滚时保持redis中数据不被清空,这里测试在Controller层加缓存。
@CacheConfig(cacheNames = “frogtest”)代表这个Controller下需要缓存的方法对应redis中的缓存名为frogtest~keys。
查询方法都用@Cacheable注解加入缓存
添加更新删除@CacheEvict(allEntries = true)注解表示执行方法时删除redis中缓存名frogtest~keys下所有缓存

redis中keys

这里写图片描述

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Spring框架通过Spring Cache提供了一套强大的缓存体系,可以轻松地实现缓存数据,提高应用程序的性能。Spring框架提供了三个主要的注解来实现缓存:@Cacheable、@CachePut和@CacheEvict。 @Cacheable注解用于将方法的结果缓存起来,以便在下次请求时,如果参数相同,则可以直接从缓存中获取结果,而不需要重新计算。该注解适用于如果计算结果比较耗时,或者需要从数据库或其他外部资源中提取数据的情况。 @CachePut注解用于更新缓存中的数据。它与@Cacheable注解类似,但不同的是,它总是更新缓存数据,而不管缓存中是否已经存在该key的值。所以,可以使用这个注解来更新缓存中的数据。 @CacheEvict注解用于从缓存中删除数据。它在需要删除缓存数据的情况下使用。它可以删除指定的key对应的缓存,也可以清空所有缓存数据。 这三个注解都有一个可选参数Named:如果指定了该参数,则缓存使用指定的名称使用。如果未指定,则使用默认的名称。可以使用不同名称的缓存来存储不同类型的数据,并使用不同的缓存策略来控制它们的存储方式。 除了Spring自带的缓存提供者之外,还可以使用其他的缓存提供者,如EhcacheRedis、Memcached等等。在使用缓存时,需要注意的是,不同的缓存提供者之间可能会有不同的限制和性能差异。因此,必须根据实际情况选择最适合的缓存提供者和缓存策略,以获取最好的性能和可靠性。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值