前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springboot+mybatis集成自定义缓存ehcache用法笔记

springboot+mybatis集成自定义缓存ehcache用法笔记

作者头像
IT技术分享社区
发布2021-09-30 10:57:31
4340
发布2021-09-30 10:57:31
举报
文章被收录于专栏:IT技术分享社区IT技术分享社区

今天小编给大家整理了springboot+mybatis集成自定义缓存ehcache用法笔记,希望对大家能有所办帮助!

一、ehcache介绍

EhCache 是一个纯Java的进程内缓存管理框架,属于开源的Java分布式缓存框架,主要用于通用缓存,Java EE和轻量级容器。

1、特点

1. 简单、快速

3. 提供多种缓存策略

4. 缓存数据可分两级:内存和磁盘

5. 缓存数据会在服务器重启的过程中重新写入磁盘

6. 可以通过RMI、可插入API等方式进行分布式缓存

7. 具有缓存和缓存管理器的侦听接口

8. 支持多缓存管理器实例,以及一个实例的多个缓存区域

9. 提供了Hibernate的缓存实现

2、应用场景

  • 单应用或对缓存访问性能要求很高的应用
  • 适合简单共享
  • 适合缓存内容不大的场景,比如MyBatis自定义缓存、系统配置信息、页面缓存。

二、springboot+mybatis集成ehcache步骤

Spring Boot 的缓存机制

高速缓存抽象不提供实际存储,并且依赖于由org.springframework.cache.Cache和org.springframework.cache.CacheManager接口实现的抽象。 Spring Boot根据实现自动配置合适的CacheManager,只要缓存支持通过@EnableCaching注解启用即可。

1、添加ehcache.xml配置文件

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <diskStore path="java.io.tmpdir" />

    <!-- 配置提供者 1、peerDiscovery,提供者方式,有两种方式:自动发现(automatic)、手动配置(manual) 2、rmiUrls,手动方式时提供者的地址,多个的话用|隔开 -->
    <cacheManagerPeerProviderFactory
        class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
        properties="peerDiscovery=manual,rmiUrls=//127.0.0.1:40002/userCache" />
    <!-- <cacheManagerPeerProviderFactory
        class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
        properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1, multicastGroupPort=4446,timeToLive=255"/>
 -->
    <!-- 配置监听器 1、hostName 主机地址 2、port 端口 3、socketTimeoutMillis socket子模块的超时时间,默认是2000ms -->
    <cacheManagerPeerListenerFactory
        class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
        properties="hostName=127.0.0.1, port=40001, socketTimeoutMillis=2000" />
    <!-- <cacheManagerPeerListenerFactory
         class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/> -->


    <defaultCache eternal="false" maxElementsInMemory="1000"
        overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
        timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" />

    <cache
        name="userCache"
        maxElementsInMemory="1000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="300"
        overflowToDisk="false"
        memoryStoreEvictionPolicy="LRU">


        <!-- 配置缓存事件监听器 replicateAsynchronously 操作是否异步,默认值为true. replicatePuts 添加操作是否同步到集群内的其他缓存,默认为true.
            replicateUpdates 更新操作是否同步到集群内的其他缓存,默认为true. replicateUpdatesViaCopy 更新之后的对象是否复制到集群中的其他缓存(true);
            replicateRemovals 删除操作是否同步到集群内的其他缓存,默认为true. -->
        <cacheEventListenerFactory
            class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
            properties="
                    replicateAsynchronously=true,
                    replicatePuts=true,
                    replicateUpdates=true,
                    replicateUpdatesViaCopy=true,
                    replicateRemovals=true " />


         <!-- 初始化缓存,以及自动设置 -->
        <bootstrapCacheLoaderFactory
            class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"
            properties="bootstrapAsynchronously=true" />

    </cache>

</ehcache>
代码语言:javascript
复制

2、配置 application.properyies

代码语言:javascript
复制
代码语言:javascript
复制
#cache 配置cache 

spring.cache.cache-names=userCache 
spring.cache.jcache.config=classpath:ehcache.xml
代码语言:javascript
复制

3、springboot启动类增加注解@EnableCaching

代码语言:javascript
复制
@SpringBootApplication
@ComponentScan(basePackages="com.ehcache")//扫描组件
@EnableCaching
public class EhcacheTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(EhcacheTestApplication.class, args);
    }
}
代码语言:javascript
复制


4、UserInfoService.java 文件增加缓存注解

代码语言:javascript
复制
代码语言:javascript
复制
@Service
public class UserInfoService {

    @Autowired
    private UserDao userDao;

    @CacheEvict(key="'user_'+#uid", value="userCache")
    public void del(String uid) {       
        userDao.del(uid);
    }

    @CachePut(key="'user_'+#user.id", value="userCache")
    public void update(User user) {
        userDao.update(user);
    }

    @Cacheable(key="'user_'+#id",value="userCache")
    public User getUserById(String id){     
        return userDao.findById(id);    }

    @CacheEvict(key="'user'",value="userCache")
    public String save(User user) {        
        return userDao.save(user);
    }
}

5、增加测试控制器TestController.java

代码语言:javascript
复制
package com.ehcache.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.ehcache.entity.User;
import com.ehcache.factory.CacheManagerFactory;
import com.ehcache.factory.UserFactory;
import com.ehcache.service.UserService;
import com.google.gson.Gson;

import net.sf.ehcache.Element;


@RestController
@RequestMapping("/CacheTest")
public class CacheTestController {
    @Autowired
    private UserService userService;
    Gson gson = new Gson();
    CacheManagerFactory cmf = CacheManagerFactory.getInstance();
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test(HttpServletRequest request){
        // 新增新用户
        String id = userService.save(UserFactory.createUser());
        User user = userService.getUserById(id);
        user.setUsername("小明");
        userService.update(user);
        // 查询该用户
        System.out.println(gson.toJson(user, User.class));      
        System.out.println();
        // 再查询该用户
        User user = userService.getUserById(uid);
        System.out.println(gson.toJson(user, User.class));
        System.out.println();
        // 更新该用户
        userService.update(user);
        // 更新成功后再查询该用户        System.out.println(gson.toJson(userService.getUserById(id), User.class));
        System.out.println();
        // 删除该用户
        userService.del(id);
        System.out.println();
        // 删除后再查询该用户        System.out.println(gson.toJson(userService.getUserById(id), User.class));
        return id;
    }
}
代码语言:javascript
复制
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-09-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 小明互联网技术分享社区 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、ehcache介绍
    • 1、特点
      • 2、应用场景
      • 二、springboot+mybatis集成ehcache步骤
        • Spring Boot 的缓存机制
          • 1、添加ehcache.xml配置文件
            • 2、配置 application.properyies
              • 3、springboot启动类增加注解@EnableCaching
                • 4、UserInfoService.java 文件增加缓存注解
                  • 5、增加测试控制器TestController.java
                  相关产品与服务
                  容器服务
                  腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
                  领券
                  问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档