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


       3a8a0e256b60abcde04e286b984dadd8.png        

今天小编给大家整理了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配置文件

<?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>

2、配置 application.properyies

#cache 配置cache 


spring.cache.cache-names=userCache 
spring.cache.jcache.config=classpath:ehcache.xml

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

@SpringBootApplication
@ComponentScan(basePackages="com.ehcache")//扫描组件
@EnableCaching
public class EhcacheTestApplication {


    public static void main(String[] args) {
        SpringApplication.run(EhcacheTestApplication.class, args);
    }
}

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

@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

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;
    }
}

IT技术分享社区

个人博客网站:https://programmerblog.xyz

c9b483006cf291d0e83e3858703cee8e.png

文章推荐程序员效率:画流程图常用的工具程序员效率:整理常用的在线笔记软件远程办公:常用的远程协助软件,你都知道吗?51单片机程序下载、ISP及串口基础知识硬件:断路器、接触器、继电器基础知识

首先,需要在pom.xml文件中添加以下依赖: ```xml <!-- Spring Boot MyBatis Oracle --> <dependency> <groupId>com.oracle.database.jdbc</groupId> <artifactId>ojdbc8</artifactId> <version>18.3.0.0</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> ``` 然后,在application.properties中配置Oracle数据库连接信息: ```properties # Oracle 数据源配置 spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/orcl spring.datasource.username=your_username spring.datasource.password=your_password ``` 接着,创建一个Mapper接口和对应的Mapper XML文件。例如,我们创建一个UserMapper接口,对应的Mapper XML文件为UserMapper.xml。 UserMapper接口: ```java public interface UserMapper { List<User> findAll(); } ``` UserMapper.xml文件: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.mapper.UserMapper"> <select id="findAll" resultType="com.example.entity.User"> select * from user </select> </mapper> ``` 最后,在Spring Boot应用程序中使用Mapper接口即可: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> findAll() { return userMapper.findAll(); } } ``` 以上就是Spring Boot和MyBatis集成Oracle数据库的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

IT技术分享社区

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

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

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

打赏作者

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

抵扣说明:

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

余额充值