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

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

导入依赖
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
 
 
  • 1
  • 2
  • 3
  • 4
配置文件
# 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
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
配置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;
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
缓存注解的使用

@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;
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87

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

redis中keys

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值