springboot-cache,缓存使用

本文档展示了如何在Spring Boot应用中使用缓存,通过`@Cacheable`和`@CacheEvict`注解实现数据缓存,并进行缓存测试。例子包括根据入参缓存、清除指定缓存以及条件性缓存。通过测试用例,演示了缓存的存取和清除流程。

适用于同一入参的缓存:

 <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.4.0</version>
        </dependency>

        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.22</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>

        <!--swagger2文档-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>com.yzgu.</groupId>
            <artifactId>common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>


        <!--springboot单元测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

 

 编写 缓存测试类


/**
 *  springboot-cache  yzgu
 */

@RequestMapping("/cache")
@Controller
public class HomeCacheController {

    @Autowired
    private TransportRecordService transportRecordService;

    @RequestMapping("/hello")
    @ResponseBody
    @Cacheable(value = "helloCache")
    public String home(){
        System.out.println("测试是否走缓存");
        return "hello world!";
    }

    /**
     * 这里根据入参可以缓存数据,只要是name 多次访问,就直接从缓存中获取,不会一直查询数据库
     * @param name
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object test(String name){
        List<TransportRecord> list = transportRecordService.getList(name);
        System.out.println("测试list是否走缓存");
        return list;
    }


        /**
         *  这里 指定的list  是 上面方法 设置的缓存
         *  cacheNames  list 上面缓存的大key
         *   key:指定要清除缓存中的某条数据 key ="123" name 参数 为123的缓存
          * allEntries=true:删除缓存中的所有数据
         *
         *   ,beforeInvocation = true 使用在方法之前执行的好处: 如果方法出现异常,缓存依旧会被删除
         *    , allEntries = true
         * @param
         * @param
         * @param
         * @return
         */
    @RequestMapping("/evict")
    @ResponseBody
    @CacheEvict(cacheNames = "list",key = "#name" ) // 清除缓存
    public Object evict(String name){
        return "ok";
    }

    /**
     *   当 name 的长度小于4  才缓存
     * @param name
     * @return
     */
    @RequestMapping("/condition")
    @ResponseBody
    @org.springframework.cache.annotation.Cacheable(value = "conditionCache", condition = "#name.length() <= 4")
    public Object test2(String name){
        System.out.println("测试condition是否走缓存");
        return "abc" + name;
    }

 

 上面的方法

1: 调用 http://localhost:9002/yzgu/cache/list?name=123

  后端会缓存 name =123的那条记录

2: 再次查询,不会走service 层

调用结果如下

3、调用 name = 456 也会缓存

http://localhost:9002/yzgu/cache/list?name=456 

4、 然后清除单条缓存  123的缓存

http://localhost:9002/yzgu/cache/evict?name=123

再次调用  http://localhost:9002/yzgu/cache/list?name=123

还是会走数据库查询

如果 想清楚所有缓存  可以指定

 

 

Spring Boot中整合Ehcache缓存,需要进行以下几个步骤: 1. 添加Ehcache依赖 在pom.xml文件中添加Ehcache依赖: ``` <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>${ehcache.version}</version> </dependency> ``` 2. 配置Ehcache缓存 在application.yml(或application.properties)文件中配置Ehcache缓存: ``` spring: cache: type: ehcache ehcache: config: classpath:ehcache.xml ``` 其中,`spring.cache.type`属性指定使用缓存类型为Ehcache,`ehcache.config`属性指定Ehcache配置文件的路径(在classpath下)。 3. 编写Ehcache配置文件 在classpath下创建`ehcache.xml`文件,配置Ehcache缓存的相关信息: ``` <ehcache> <diskStore path="java.io.tmpdir"/> <defaultCache maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" transactionalMode="off"> </defaultCache> <cache name="userCache" maxEntriesLocalHeap="1000" maxEntriesLocalDisk="10000" eternal="false" diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" transactionalMode="off"> </cache> </ehcache> ``` 其中,`defaultCache`为默认缓存配置,`cache`为自定义缓存配置。 4. 在代码中使用缓存 在需要使用缓存的方法上添加`@Cacheable`注解,指定缓存名称和缓存key: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override @Cacheable(value = "userCache", key = "#id") public User getUserById(Integer id) { return userDao.getUserById(id); } // ... } ``` 其中,`value`属性指定缓存名称,`key`属性为缓存key表达式,可以使用Spring表达式语言(SpEL)进行动态表达。 以上就是在Spring Boot中整合Ehcache缓存的步骤,通过使用Ehcache缓存可以有效地提高应用程序的性能和响应速度。
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yzgu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值