0
点赞
收藏
分享

微信扫一扫

SpringBoot中整合redis(windows版)做缓存

星河出山 2022-01-11 阅读 80

目录

导入依赖

配置文件配置redis连接以及其他

开启缓存

测试

@Cacheable用于查询

@CachePut用于增加或修改

@CacheEvict用于删除方法

精华(一定要看)


记得开启redis

导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

配置文件配置redis连接以及其他

密码默认为空

spring
  redis:
    database: 0
    host: localhost
    port: 6379
    password:

开启缓存

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.cache.interceptor.KeyGenerator;
import java.lang.reflect.Method;

/**
 * @author 刘通
 * @date 2022年01月11日 20:11
 */
@Configuration
@EnableCaching
public class RedisConfig{

}

测试

开启sql打印

@Cacheable用于查询

将结果缓存起来

    @Cacheable(value="tag")
    @RequestMapping("mysql2")
    public ArrayList<Tags> get2(){
        return test2.getTags();
    }

第一次访问mysql2时打印输出sql,代表已经查询

 第二次访问mysql2时无sql打印,代表已经缓存

@CachePut用于增加或修改

直接执行方法体 - 将结果缓存起来

我们删掉缓存(在redis客户端用flushall命令),重启项目

    @Cacheable(value="tag",key = "#id")
    @RequestMapping("getById")
    public Tags get2ByID(@RequestParam("id") int id){
        return test2.getTagsById(id);
    }

    @CachePut(value="tag",key = "#tags.id")
    @RequestMapping(value = "update",method = RequestMethod.POST)
    public Tags get2ByID(@RequestBody Tags tags){
        test2.update(tags);
        return tags;
    }

 依次执行getById---->update----->getById  (相同的id)

@CacheEvict用于删除方法

@CacheEvict是用来标注在需要清除缓存元素的方法或类上的。当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。

依次执行

mysql2---->delete----->mysql2

    @Cacheable(value="tag")
    @RequestMapping("mysql2")
    public ArrayList<Tags> get2(){
        return test2.getTags();
    }


    @CacheEvict(value = "tag",allEntries=true)
    @RequestMapping(value = "delete",method = RequestMethod.GET)
    public int delete(@RequestParam int id){
        return test2.deleteTag(id);
    }

 说明@CacheEvict(value = "tag",allEntries=true)使缓存清除。

精华(一定要看)

  • 使用@CachePut,key一定要设置和@Cacheable的key一致!否则使用之后@Cacheable去缓存查,会查不到
  • 使用@CachePut时,方法返回值要和@Cacheable方法返回值相同,否则出现类型转换异常
举报

相关推荐

0 条评论