一、springboot缓存简介

在 Spring Boot中,通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManager),Spring Boot根据下面的顺序去侦测缓存提供者:
* Generic
* JCache (JSR-107)
* EhCache 2.x
* Hazelcast
* Infinispan
* Redis
* Guava
* Simple

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

二、实例

1、application.properyies

server.port=8850

#cache 多个用逗号分开
spring.cache.cache-names=userCache
spring.cache.jcache.config=classpath:ehcache.xml # datasource
spring.datasource.name=ehcahcetest
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3312/ehcahcetest
spring.datasource.username=root
spring.datasource.password=123456 # mybatis
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.config-location=classpath:mybatis/mybatis-config.xml
#mybatis.type-aliases-package=

2、springboot启动类

 @SpringBootApplication
@ComponentScan(basePackages="com.ehcache")//扫描组件
@EnableCaching
public class EhcacheTestApplication { public static void main(String[] args) {
SpringApplication.run(EhcacheTestApplication.class, args);
}
}

3、加了缓存注解的service

 @Service
public class UserService { @Autowired
private UserDao userDao; @CacheEvict(key="'user_'+#uid", value="userCache")
public void del(String uid) {
// TODO Auto-generated method stub
userDao.del(uid);
} @CachePut(key="'user_'+#user.uid", value="userCache")
public void update(User user) {
userDao.update(user);
} @Cacheable(key="'user_'+#uid",value="userCache")
public User getUserById(String uid){
System.err.println("缓存里没有"+uid+",所以这边没有走缓存,从数据库拿数据");
return userDao.findById(uid); } @CacheEvict(key="'user'",value="userCache")
public String save(User user) {
// TODO Auto-generated method stub
return userDao.save(user);
} }

4、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>

5、OperationController.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("/o")
public class OperationController { @Autowired
private UserService userService; Gson gson = new Gson(); CacheManagerFactory cmf = CacheManagerFactory.getInstance(); @RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(HttpServletRequest request){ // 保存一个新用户
String uid = userService.save(UserFactory.createUser());
User user = userService.getUserById(uid);
user.setUsername("xiaoli");
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(uid), User.class));
System.out.println();
// 删除该用户
userService.del(uid);
System.out.println();
// 删除好了再查询该用户
System.out.println(gson.toJson(userService.getUserById(uid), User.class));*/ // 再保存一个新用户
// String uid1 = userService.save(UserFactory.createUser()); return uid;
} @RequestMapping(value = "/test1", method = RequestMethod.GET)
public String test1(HttpServletRequest request,String key){ String res = ""; Element element = cmf.getElement("userCache", "map");
if(element == null){
Map<String, String> map = new HashMap<String, String>();
map.put(key, key);
cmf.setElement("userCache", new Element("map", map));
}else{
Map<String, String> map = (Map<String, String>) element.getValue();
res = map.get(key);
if(res == null){
map.put(key, key);
// 多次测试发现,存在同名Element是,重复put的是无法复制的,因此当遇到两个节点同步不上的时候,先remove后put。
cmf.getCache("userCache").remove("map");
cmf.setElement("userCache", new Element("map", map));
res = "0;null";
}
}
return res;
} }

springboot+mybatis+ehcache实现缓存数据的更多相关文章

  1. Shiro+springboot+mybatis+EhCache(md5+salt+散列)认证与授权-03

    从上文:Shiro+springboot+mybatis(md5+salt+散列)认证与授权-02 当每次进行刷新时,都会从数据库重新查询数据进行授权操作,这样无疑给数据库造成很大的压力,所以需要引入 ...

  2. MyBatis ehcache二级缓存

    ehcache二级缓存的开启步骤: 1.导入jar 2.在映射文件中指定用的哪个缓存 3.加一个配置文件,这个配置文件在ehcache jar包中就有 使增删改对二级缓存不刷新: 对一级缓存没有用的, ...

  3. Springboot + Mybatis + Ehcache

    最近在做一个项目,为处理并发性较差的问题,使用了Mybatis二级缓存 但在多表联合查询的情况下,Mybatis二级缓存是存在着数据脏读的问题的 两天就是在想办法解决这个数据脏读的问题 考虑到简易性. ...

  4. springboot mybatis redis 二级缓存

    前言 什么是mybatis二级缓存? 二级缓存是多个sqlsession共享的,其作用域是mapper的同一个namespace. 即,在不同的sqlsession中,相同的namespace下,相同 ...

  5. 【spring-boot】spring-boot 整合 ehcache 实现缓存机制

    方式一:老 不推荐 参考:https://www.cnblogs.com/lic309/p/4072848.html /*************************第一种   引入 ehcach ...

  6. 【spring-boot】spring-boot整合ehcache实现缓存机制

    EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心 ...

  7. spring-boot整合ehcache实现缓存机制

    EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心 ...

  8. springboot+mybatis+redis实现分布式缓存

    大家都知道springboot项目都是微服务部署,A服务和B服务分开部署,那么它们如何更新或者获取共有模块的缓存数据,或者给A服务做分布式集群负载,如何确保A服务的所有集群都能同步公共模块的缓存数据, ...

  9. Springboot整合Ehcache 解决Mybatis二级缓存数据脏读 -详细

    前面有写了一篇关于这个,但是这几天又改进了一点,就单独一篇在详细说明一下 配置 application.properties ,启用Ehcache # Ehcache缓存 spring.cache.t ...

随机推荐

  1. STL - list(双向链表)

    List简介 list是一个双向链表容器,可高效地进行插入删除元素. list不可以随机存取元素,所以不支持at.(pos)函数与[]操作符.It++(ok) it+5(err) #include & ...

  2. g++和gcc的相同点和区别

    gcc和g++的区别和联系 gcc和g++都是GNU(一个组织)的编译器. 1.对于.c后缀的文件,gcc把它当做是C程序:g++当做是C++程序: 2.对于.cpp后缀的文件,gcc和g++都会当做 ...

  3. CentOS删除自带的java,安装新java

    [root@localhost ~]# java -version java version "1.4.2″ gij (GNU libgcj) version 4.1.2 20071124 ...

  4. Java进阶(十五)Java中设置session的详细解释

    Java中设置session的详细解释 简单通俗的讲session就是象一个临时的容器,用来存放临时的东西.从你登陆开始就保存在session里,当然你可以自己设置它的有效时间和页面,举个简单的例子: ...

  5. 使用Android Studio手把手教你将应用打包+代码混淆

    最近几天用Google的Design库写了个App,使用Android Studio将app打包时遇到的几个瓶颈,所以把详细步骤写入下来. AS中怎么获取应用签名 这和eclipse不同,eclips ...

  6. 前端开发我为什么选择cordova

    cordova与phonegap有什么关系? phoengap 官方网址:http://phonegap.com 如果能了解一个框架的兴起还是一件比较有趣的事.08年一次ios开发者大会上来自Nito ...

  7. Supervisor安装、配置、开启启动

    1.安装Python包管理工具(easy_install) wget --no-check-certificate https://bootstrap.pypa.io/ez_setup.py -O - ...

  8. ScrollView的顶部下拉和底部上拉回弹效果

    要实现ScrollView的回弹效果,需要对其进行触摸事件处理.先来看一下简单的效果: 根据Android的View事件分发处理机制,下面对dispatchTouchEvent进行详细分析: 在加载布 ...

  9. MySQL运维工具

    Mysql运维过程中设计的各类工具以及各个场景的的命令行的分类.大体总结如下的xmind图片(.xmind附件 加 Q1123654342). 大体上分为: 实例管理工具.高可用工具.慢日志查询工具. ...

  10. SQL SERVER 锁资源问题

    1204: cannot obtain a LOCK resource 在sql server 锁资源的限制基本是自动优化调整.如果调整过参数,可能在系统大批量查询的时候出现以上错误,或者是 alwa ...