【过程记录】springboot中使用EhcacheCache+mybatis
生活随笔
收集整理的這篇文章主要介紹了
【过程记录】springboot中使用EhcacheCache+mybatis
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 目錄和依賴
- 相關配置
- 增刪改查操作
- 測試類:
- 一些注意點
目錄和依賴
<dependencies><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.2</version></dependency><!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>2.0.0-alpha1</version><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies><!--在build中配置resources,來防止我們資源導出失敗的問題--><build><resources><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>true</filtering></resource><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>true</filtering></resource></resources></build>數據表:
相關配置
1.mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!--引入外部配置文件--><properties resource="db.properties"/><settings><setting name="mapUnderscoreToCamelCase" value="true"/><setting name="cacheEnabled" value="true"/><setting name="logImpl" value="STDOUT_LOGGING"/></settings><typeAliases><typeAlias type="com.hou.pojo.User" alias="User"></typeAlias></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment></environments><!--綁定接口--><mappers><mapper class="com.hou.mapper.UserMapper"></mapper></mappers> </configuration>2.log4j.properties
log4j.rootLogger=debug, stdout, Rlog4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout# Pattern to output the caller's file name and line number. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%nlog4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=example.loglog4j.appender.R.MaxFileSize=100KB # Keep one backup file log4j.appender.R.MaxBackupIndex=5log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n3.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"updateCheck="false"><!--diskStore:為緩存路徑,ehcache分為內存和磁盤兩級,此屬性定義磁盤的緩存位置。參數解釋如下:user.home – 用戶主目錄user.dir – 用戶當前工作目錄java.io.tmpdir – 默認臨時文件路徑--><diskStore path="java.io.tmpdir/Tmp_EhCache"/><!--defaultCache:默認緩存策略,當ehcache找不到定義的緩存時,則使用這個緩存策略。只能定義一個。--><!--name:緩存名稱。maxElementsInMemory:緩存最大數目maxElementsOnDisk:硬盤最大緩存個數。eternal:對象是否永久有效,一但設置了,timeout將不起作用。overflowToDisk:是否保存到磁盤,當系統當機時timeToIdleSeconds:設置對象在失效前的允許閑置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閑置時間無窮大。timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介于創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。diskPersistent:是否緩存虛擬機重啟期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩沖區。diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置為FIFO(先進先出)或是LFU(較少使用)。clearOnFlush:內存數量最大時是否清除。memoryStoreEvictionPolicy:可選策略有:LRU(最近最少使用,默認策略)、FIFO(先進先出)、LFU(最少訪問次數)。FIFO,first in first out,這個是大家最熟的,先進先出。LFU, Less Frequently Used,就是上面例子中使用的策略,直白一點就是講一直以來最少被使用的。如上面所講,緩存的元素有一個hit屬性,hit值最小的將會被清出緩存。LRU,Least Recently Used,最近最少使用的,緩存的元素有一個時間戳,當緩存容量滿了,而又需要騰出地方來緩存新的元素的時候,那么現有緩存元素中時間戳離當前時間最遠的元素將被清出緩存。--><defaultCacheeternal="false"maxElementsInMemory="10000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="1800"timeToLiveSeconds="259200"memoryStoreEvictionPolicy="LRU"/><!-- 在mybatis中使用二級緩存--><cachename="cloud_user"eternal="false"maxElementsInMemory="5000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="1800"timeToLiveSeconds="1800"memoryStoreEvictionPolicy="LRU"/></ehcache>db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3308/data1?userSSL=true&userUnicode=true&characterEncoding=UTF-8 username=heziyi password=123456mybatis配置:
//sqlSessionFactory --> sqlSession public class MybatisUtils {private static SqlSessionFactory sqlSessionFactory;static {try {//使用mybatis第一步:獲取sqlSessionFactory對象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {e.printStackTrace();}}public static SqlSession getSqlSession(){return sqlSessionFactory.openSession(true);}}增刪改查操作
pojo:
@Data public class User implements Serializable {private int id;private String name;private String pwd;public User(int id, String name, String pwd) {this.id = id;this.name = name;this.pwd = pwd;} }mapper和接口:
public interface UserMapper {User queryUserByid(@Param("id") int id);} <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.hou.mapper.UserMapper"><cache type="org.mybatis.caches.ehcache.EhcacheCache"/><select id="queryUserByid" resultType="User">select * from data1.user where id = #{id}</select><update id="updateUser" parameterType="User">update data1.user set name=#{name}, pwd=#{pwd} where id=#{id}</update> </mapper>測試類:
public class MyTest {@Testpublic void addBlog(){SqlSession sqlSession = MybatisUtils.getSqlSession();SqlSession sqlSession1 = MybatisUtils.getSqlSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);User user = userMapper.queryUserByid(1);System.out.println(user);sqlSession.close();UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);User user1 = userMapper1.queryUserByid(1);System.out.println(user1);//User(id=1, name=你好, pwd=345678)System.out.println(user==user1);//trueUser u3 = userMapper1.queryUserByid(2);System.out.println(u3);sqlSession1.close();}}運行結果:
一些注意點
總結
以上是生活随笔為你收集整理的【过程记录】springboot中使用EhcacheCache+mybatis的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转载】java中泛型使用详解
- 下一篇: 【java学习】Arraylist和Li