SpringCloud(第 045 篇)鏈接Mysql數據庫簡單的集成Mybatis、ehcache框架採用MapperXml訪問數據庫
-
一、大致介紹
1、數據庫頻繁的操作也會影響性能,所以本章節準備給訪問數據庫前面添加一層緩存操作;
2、雖然說緩存框架存在很多且各有各的優勢,本章節僅僅只是爲了測試緩存的操作實現,所以就採用了一個簡單的緩存框架ehcache;
二、實現步驟
2.1 添加 maven 引用包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>springms-provider-user-mysql-mybatis-mapper-ehcache</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.springms.cloud</groupId>
<artifactId>springms-spring-cloud</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- 訪問數據庫模塊 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- web模塊 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MYSQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Mybatis依賴 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 開啓 cache 緩存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- ehcache 緩存模塊 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
</dependencies>
</project>
2.2 添加應用配置文件(springms-provider-user-mysql-mybatis-mapper-ehcache\src\main\resources\application.yml)
server:
port: 8385
spring:
application:
name: springms-provider-user-mysql-mybatis-mapper-ehcache #全部小寫
#####################################################################################################
# mysql 屬性配置
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://120.77.176.162:3306/hmilyylimh
username: root
password: mysqladmin
# jpa:
# hibernate:
# #ddl-auto: create #ddl-auto:設爲create表示每次都重新建表
# ddl-auto: update #ddl-auto:設爲update表示每次都不會重新建表
# show-sql: true
#####################################################################################################
#####################################################################################################
# mybatis mapper xml 配置
mybatis:
# mybatis.type-aliases-package:指定domain類的基包,即指定其在*Mapper.xml文件中可以使用簡名來代替全類名(看後邊的UserMapper.xml介紹)
type-aliases-package:
mapper-locations: classpath:mybatis/mapper/*.xml
config-location: classpath:mybatis/mybatis-config.xml
#####################################################################################################
#####################################################################################################
# 打印日誌
logging:
level:
root: INFO
org.hibernate: INFO
org.hibernate.type.descriptor.sql.BasicBinder: TRACE
org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
com.springms: DEBUG
#####################################################################################################
2.3 添加mybatis配置文件(springms-provider-user-mysql-mybatis-mapper-ehcache/src/main/java/com/springms/cloud/entity/User.java)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="callSettersOnNulls" value="true"/>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="NULL"/>
</settings>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
<typeAlias alias="User" type="com.springms.cloud.entity.User"/>
</typeAliases>
</configuration>
2.4 添加用戶mapperxml映射文件(springms-provider-user-mysql-mybatis-mapper-ehcache/src/main/java/com/springms/cloud/entity/User.java)
<?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.springms.cloud.mapper.IUserMapper">
<resultMap id="result" type="User">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="username" property="username" jdbcType="VARCHAR"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="TINYINT"/>
<result column="balance" property="balance" jdbcType="VARCHAR"/>
</resultMap>
<!-- 若不需要自動返回主鍵,將useGeneratedKeys="true" keyProperty="id"去掉即可(當然如果不需要自動返回主鍵,直接用註解即可) -->
<insert id="insertUser" parameterType="User" useGeneratedKeys="false" keyProperty="id" >
<![CDATA[
INSERT INTO user
(
username,
name,
age,
balance
)
VALUES
(
#{username, jdbcType=VARCHAR},
#{name, jdbcType=VARCHAR},
#{age, jdbcType=TINYINT},
#{balance, jdbcType=VARCHAR}
)
]]>
</insert>
<select id="findUserById" resultMap="result" parameterType="Long">
select * from user
where id = #{id,jdbcType=BIGINT}
</select>
<select id="findAllUsers" resultMap="result">
select * from user
</select>
<select id="deleteUser" parameterType="Long">
DELETE from user where id = #{id}
</select>
<update id="updateUser" parameterType="User" >
update user set userName=#{username},name=#{name},age=#{age},balance=#{balance} where id=#{id}
</update>
</mapper>
2.5 添加緩存配置文件(springms-provider-user-mysql-mybatis-mapper-ehcache/src/main/resources/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">
<defaultCache
eternal="false"
maxElementsInMemory="900"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="500"
memoryStoreEvictionPolicy="LRU" />
<!-- 這裏的 users 緩存空間是爲了下面的 demo 做準備 -->
<cache
name="cache-b"
eternal="false"
maxElementsInMemory="200"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="400"
memoryStoreEvictionPolicy="LRU" />
</ehcache>
<!--Ehcache 相關資料:-->
<!--diskStore:爲緩存路徑,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,最近最少使用的,緩存的元素有一個時間戳,當緩存容量滿了,而又需要騰出地方來緩存新的元素的時候,那麼現有緩存元素中時間戳離當前時間最遠的元素將被清出緩存。-->
<!--一般情況下,我們在Sercive層進行對緩存的操作。先介紹 Ehcache 在 Spring 中的註解:在支持 Spring Cache 的環境下,-->
<!--* @Cacheable : Spring在每次執行前都會檢查Cache中是否存在相同key的緩存元素,如果存在就不再執行該方法,而是直接從緩存中獲取結果進行返回,否則纔會執行並將返回結果存入指定的緩存中。-->
<!--* @CacheEvict : 清除緩存。-->
<!--* @CachePut : @CachePut也可以聲明一個方法支持緩存功能。使用@CachePut標註的方法在執行前不會去檢查緩存中是否存在之前執行過的結果,而是每次都會執行該方法,並將執行結果以鍵值對的形式存入指定的緩存中。-->
<!--* 這三個方法中都有兩個主要的屬性:value 指的是 ehcache.xml 中的緩存策略空間;key 指的是緩存的標識,同時可以用 # 來引用參數。-->
2.6 添加實體用戶類User(sspringms-provider-user-mysql-mybatis-mapper-ehcache/src/main/java/com/springms/cloud/entity/User.java)
package com.springms.cloud.entity;
public class User {
private Long id;
private String username;
private String name;
private Integer age;
private String balance;
/** 來自於哪裏,默認來自於數據庫 */
private String from = "";
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return this.age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getBalance() {
return this.balance;
}
public void setBalance(String balance) {
this.balance = balance;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", name='" + name + '\'' +
", age=" + age +
", balance='" + balance + '\'' +
", from='" + from + '\'' +
'}';
}
}
2.7 添加用戶mapper接口(springms-provider-user-mysql-mybatis-mapper-ehcache/src/main/java/com/springms/cloud/mapper/IUserMapper.java)
package com.springms.cloud.mapper;
import com.springms.cloud.entity.User;
import java.util.List;
/**
* 用戶 mybatis 接口文件。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017-10-19
*
*/
public interface IUserMapper {
User findUserById(Long id);
List<User> findAllUsers();
int insertUser(User user);
int updateUser(User user);
int deleteUser(Long id);
}
2.8 添加用戶DAO接口類(springms-provider-user-mysql-mybatis-mapper-ehcache/src/main/java/com/springms/cloud/dao/IUserDao.java)
package com.springms.cloud.dao;
import com.springms.cloud.entity.User;
import java.util.List;
/**
* 簡單用戶鏈接Mysql數據庫微服務(通過@Repository註解標註該類爲持久化操作對象)。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017-10-19
*
*/
public interface IUserDao {
User findUserById(Long id);
List<User> findAllUsers();
int insertUser(User user);
int updateUser(User user);
int deleteUser(Long id);
}
2.9 添加用戶DAO接口類實現類(springms-provider-user-mysql-mybatis-mapper-ehcache/src/main/java/com/springms/cloud/dao/impl/UserDaoImpl.java)
package com.springms.cloud.dao.impl;
import com.springms.cloud.dao.IUserDao;
import com.springms.cloud.entity.User;
import com.springms.cloud.mapper.IUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 簡單用戶鏈接Mysql數據庫微服務(通過@Repository註解標註該類爲持久化操作對象)。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017-10-19
*
*/
@Repository
public class UserDaoImpl implements IUserDao {
@Autowired
private IUserMapper iUserMapper;
@Override
public User findUserById(Long id) {
return iUserMapper.findUserById(id);
}
@Override
public List<User> findAllUsers() {
return iUserMapper.findAllUsers();
}
@Override
public int insertUser(User user) {
return iUserMapper.insertUser(user);
}
@Override
public int updateUser(User user) {
return iUserMapper.updateUser(user);
}
@Override
public int deleteUser(Long id) {
return iUserMapper.deleteUser(id);
}
}
2.10 添加用戶Service接口類(springms-provider-user-mysql-mybatis-mapper-ehcache/src/main/java/com/springms/cloud/service/IUserService.java)
package com.springms.cloud.service;
import com.springms.cloud.entity.User;
import java.util.List;
/**
* 簡單用戶鏈接Mysql數據庫微服務(通過@Service註解標註該類爲持久化操作對象)。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017-10-19
*
*/
public interface IUserService {
User findUserById(Long id);
List<User> findAllUsers();
int insertUser(User user);
int updateUser(User user);
int deleteUser(Long id);
}
2.11 添加用戶Service接口實現類(springms-provider-user-mysql-mybatis-mapper-ehcache/src/main/java/com/springms/cloud/service/impl/UserServiceImpl.java)
package com.springms.cloud.service.impl;
import com.springms.cloud.dao.IUserDao;
import com.springms.cloud.entity.User;
import com.springms.cloud.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 簡單用戶鏈接Mysql數據庫微服務(通過@Service註解標註該類爲持久化操作對象)。<br/>
*
* <li>注意:CACHE_KEY、CACHE_NAME_B 的單引號不能少,否則會報錯,被識別是一個對象。</li>
*
* <li>value 指的是 ehcache.xml 中的緩存策略空間;key 指的是緩存的標識</li>
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017-10-19
*
*/
@Service
public class UserServiceImpl implements IUserService {
private static final String CACHE_KEY = "'user'";
private static final String CACHE_NAME_B = "cache-b";
//* @Cacheable : Spring在每次執行前都會檢查Cache中是否存在相同key的緩存元素,如果存在就不再執行該方法,而是直接從緩存中獲取結果進行返回,否則纔會執行並將返回結果存入指定的緩存中。
//* @CacheEvict : 清除緩存。
//* @CachePut : @CachePut也可以聲明一個方法支持緩存功能。使用@CachePut標註的方法在執行前不會去檢查緩存中是否存在之前執行過的結果,而是每次都會執行該方法,並將執行結果以鍵值對的形式存入指定的緩存中。
@Autowired
IUserDao iUserDao;
/**
* 查找用戶數據
*
* @param id
* @return
*/
@Cacheable(value=CACHE_NAME_B, key="'user_'+#id")
@Override
public User findUserById(Long id) {
return iUserDao.findUserById(id);
}
@Override
public List<User> findAllUsers() {
return iUserDao.findAllUsers();
}
/**
* 保存用戶數據
*
* @param user
* @return
*/
@CacheEvict(value=CACHE_NAME_B, key=CACHE_KEY)
@Override
public int insertUser(User user) {
return iUserDao.insertUser(user);
}
/**
* 更新用戶數據
*
* @param user
* @return
*/
@CachePut(value = CACHE_NAME_B, key = "'user_'+#user.id")
@Override
public int updateUser(User user) {
return iUserDao.updateUser(user);
}
/**
* 刪除用戶數據
*
* @param id
* @return
*/
@CacheEvict(value = CACHE_NAME_B, key = "'user_' + #id") //這是清除緩存
@Override
public int deleteUser(Long id) {
return iUserDao.deleteUser(id);
}
}
2.12 添加緩存配置Config(springms-provider-user-mysql-mybatis-mapper-ehcache/src/main/java/com/springms/cloud/config/CacheConfiguration.java)
package com.springms.cloud.config;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
/**
* 緩存配置。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017-10-19
*
*/
@Configuration
@EnableCaching//標註啓動緩存.
public class CacheConfiguration {
/**
* ehcache 主要的管理器
*
* @param bean
* @return
*/
@Bean
public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){
System.out.println("CacheConfiguration.ehCacheCacheManager()");
return new EhCacheCacheManager(bean.getObject());
}
/*
* 據shared與否的設置,
* Spring分別通過CacheManager.create()
* 或new CacheManager()方式來創建一個ehcache基地.
*
* 也說是說通過這個來設置cache的基地是這裏的Spring獨用,還是跟別的(如hibernate的Ehcache共享)
*
*/
@Bean
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){
System.out.println("CacheConfiguration.ehCacheManagerFactoryBean()");
EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean ();
cacheManagerFactoryBean.setConfigLocation (new ClassPathResource("ehcache.xml"));
cacheManagerFactoryBean.setShared(true);
return cacheManagerFactoryBean;
}
}
2.13 添加用戶Web訪問層Controller(springms-provider-user-mysql-mybatis-mapper/src/main/java/com/springms/cloud/controller/ProviderUserMysqlMybatisMapperController.java)
package com.springms.cloud.controller;
import com.springms.cloud.entity.User;
import com.springms.cloud.service.IUserService;
import org.hibernate.cache.CacheException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 用戶微服務Controller。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017-10-19
*
*/
@RestController
public class ProviderUserMysqlMybatisMapperEhCacheController {
private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(ProviderUserMysqlMybatisMapperEhCacheController.class);
@Autowired
private IUserService iUserService;
@GetMapping("/user/{id}")
public User findUserById(@PathVariable Long id) {
return this.iUserService.findUserById(id);
}
@GetMapping("/user/list")
public List<User> findUserList() {
return this.iUserService.findAllUsers();
}
/**
* 添加一個student,使用postMapping接收post請求
*
* http://localhost:8330/simple/addUser?username=user11&age=11&balance=11
*
* @return
*/
@PostMapping("/user/addUser")
public User addUser(@RequestParam(value = "username", required=false) String username, @RequestParam(value = "age", required=false) Integer age, @RequestParam(value = "balance", required=false) String balance){
User user=new User();
user.setUsername(username);
user.setName(username);
user.setAge(age);
user.setBalance(balance);
int result = iUserService.insertUser(user);
if(result > 0){
return user;
}
user.setId(0L);
user.setName(null);
user.setUsername(null);
user.setBalance(null);
return user;
}
@GetMapping("/user/ehcache")
public String ehcache() {
Logger.info("=========== 進行Encache緩存測試");
List<User> allUsers = iUserService.findAllUsers();
User lastUser = allUsers.get(allUsers.size() - 1);
String lastUserUsername = lastUser.getUsername();
String indexString = lastUserUsername.substring(4);
Logger.info("=========== ====生成第一個用戶====");
User user1 = new User();
//生成第一個用戶的唯一標識符 UUID
user1.setName("user" + (Integer.parseInt(indexString) + 1));
user1.setUsername(user1.getName());
user1.setAge(1000);
user1.setBalance("1000");
if (iUserService.insertUser(user1) == 0){
throw new CacheException("用戶對象插入數據庫失敗");
}
allUsers = iUserService.findAllUsers();
lastUser = allUsers.get(allUsers.size() - 1);
Long lastUserId = lastUser.getId();
//第一次查詢
Logger.info("=========== 第一次查詢");
Logger.info("=========== 第一次查詢結果: {}", iUserService.findUserById(lastUserId));
//通過緩存查詢
Logger.info("=========== 通過緩存第 1 次查詢");
Logger.info("=========== 通過緩存第 1 次查詢結果: {}", iUserService.findUserById(lastUserId));
Logger.info("=========== 通過緩存第 2 次查詢");
Logger.info("=========== 通過緩存第 2 次查詢結果: {}", iUserService.findUserById(lastUserId));
Logger.info("=========== 通過緩存第 3 次查詢");
Logger.info("=========== 通過緩存第 3 次查詢結果: {}", iUserService.findUserById(lastUserId));
Logger.info("=========== ====準備修改數據====");
User user2 = new User();
user2.setName(lastUser.getName());
user2.setUsername(lastUser.getUsername());
user2.setAge(lastUser.getAge() + 1000);
user2.setBalance(String.valueOf(user2.getAge()));
user2.setId(lastUserId);
try {
int result = iUserService.updateUser(user2);
Logger.info("=========== ==== 修改數據 == {} ==", (result > 0? "成功":"失敗"));
} catch (CacheException e){
e.printStackTrace();
}
Logger.info("=========== ====修改後再次查詢數據");
Object resultObj = iUserService.findUserById(lastUser.getId());
Logger.info("=========== ====修改後再次查詢數據結果: {}", resultObj);
return "success";
}
}
2.14 添加微服務啓動類(springms-provider-user-mysql-mybatis-mapper-ehcache/src/main/java/com/springms/cloud/MsProviderUserMysqlMybatisMapperEhCacheApplication.java)
package com.springms.cloud;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
/**
* 鏈接Mysql數據庫簡單的集成Mybatis、ehcache框架採用MapperXml訪問數據庫。
*
* 簡單用戶鏈接Mysql數據庫微服務(通過 mybatis 鏈接 mysql 並用 MapperXml 編寫數據訪問,並且通過 EhCache 緩存來訪問)。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017-10-19
*
*/
@SpringBootApplication
@MapperScan("com.springms.cloud.mapper.**")
@EnableCaching
public class MsProviderUserMysqlMybatisMapperEhCacheApplication {
public static void main(String[] args) {
SpringApplication.run(MsProviderUserMysqlMybatisMapperEhCacheApplication.class, args);
System.out.println("【【【【【【 鏈接MysqlMybatisMapperEhCache數據庫微服務 】】】】】】已啓動.");
}
}
三、測試
/****************************************************************************************
注意:Mybatis 需要加上 entity 等註解纔可以使用,不然啓動都會報錯;
@MapperScan("com.springms.cloud.mapper.**") 或者在每個 Mapper 接口文件上添加 @Mapper 也可以;
一、簡單用戶鏈接Mysql數據庫微服務(通過 mybatis 鏈接 mysql 並用 MapperXml 編寫數據訪問,並且通過 EhCache 緩存來訪問):
1、啓動 springms-provider-user-mysql-mybatis-mapper-ehcache 模塊服務,啓動1個端口;
2、在瀏覽器輸入地址 http://localhost:8385/user/10 可以看到用戶ID=10的信息成功的被打印出來;
3、使用 IDEA 自帶工具 Test Restful WebService 發送 HTTP POST 請求,並添加 username、age、balance三個參數,然後執行請求,並去 mysql 數據庫查看數據是否存在,正常情況下 mysql 數據庫剛剛插入的數據成功了:
4、使用 REST Client 執行 "/user/ehcache" 接口,也正常將 mysql 數據庫中所有的用戶信息打印出來了,並且打印的信息如下:
5、在瀏覽器輸入地址 http://localhost:8385/user/ehcache 可以看到如下信息被打印出來;
2017-10-19 17:48:54.561 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== 進行Encache緩存測試
2017-10-19 17:48:54.610 DEBUG 2736 --- [nio-8385-exec-1] c.i.c.mapper.IUserMapper.findAllUsers : ==> Preparing: select * from user
2017-10-19 17:48:54.629 DEBUG 2736 --- [nio-8385-exec-1] c.i.c.mapper.IUserMapper.findAllUsers : ==> Parameters:
2017-10-19 17:48:54.657 DEBUG 2736 --- [nio-8385-exec-1] c.i.c.mapper.IUserMapper.findAllUsers : <== Total: 65
2017-10-19 17:48:54.658 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== ====生成第一個用戶====
2017-10-19 17:48:54.661 DEBUG 2736 --- [nio-8385-exec-1] c.i.cloud.mapper.IUserMapper.insertUser : ==> Preparing: INSERT INTO user ( username, name, age, balance ) VALUES ( ?, ?, ?, ? )
2017-10-19 17:48:54.662 DEBUG 2736 --- [nio-8385-exec-1] c.i.cloud.mapper.IUserMapper.insertUser : ==> Parameters: user66(String), user66(String), 1000(Integer), 1000(String)
2017-10-19 17:48:54.678 DEBUG 2736 --- [nio-8385-exec-1] c.i.cloud.mapper.IUserMapper.insertUser : <== Updates: 1
2017-10-19 17:48:54.691 DEBUG 2736 --- [nio-8385-exec-1] c.i.c.mapper.IUserMapper.findAllUsers : ==> Preparing: select * from user
2017-10-19 17:48:54.692 DEBUG 2736 --- [nio-8385-exec-1] c.i.c.mapper.IUserMapper.findAllUsers : ==> Parameters:
2017-10-19 17:48:54.707 DEBUG 2736 --- [nio-8385-exec-1] c.i.c.mapper.IUserMapper.findAllUsers : <== Total: 66
2017-10-19 17:48:54.708 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== 第一次查詢
2017-10-19 17:48:54.714 DEBUG 2736 --- [nio-8385-exec-1] c.i.c.mapper.IUserMapper.findUserById : ==> Preparing: select * from user where id = ?
2017-10-19 17:48:54.714 DEBUG 2736 --- [nio-8385-exec-1] c.i.c.mapper.IUserMapper.findUserById : ==> Parameters: 147(Long)
2017-10-19 17:48:54.721 DEBUG 2736 --- [nio-8385-exec-1] c.i.c.mapper.IUserMapper.findUserById : <== Total: 1
2017-10-19 17:48:54.722 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== 第一次查詢結果: User{id=147, username='user66', name='user66', age=1000, balance='1000', from=''}
2017-10-19 17:48:54.722 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== 通過緩存第 1 次查詢
2017-10-19 17:48:54.723 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== 通過緩存第 1 次查詢結果: User{id=147, username='user66', name='user66', age=1000, balance='1000', from=''}
2017-10-19 17:48:54.723 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== 通過緩存第 2 次查詢
2017-10-19 17:48:54.724 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== 通過緩存第 2 次查詢結果: User{id=147, username='user66', name='user66', age=1000, balance='1000', from=''}
2017-10-19 17:48:54.724 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== 通過緩存第 3 次查詢
2017-10-19 17:48:54.724 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== 通過緩存第 3 次查詢結果: User{id=147, username='user66', name='user66', age=1000, balance='1000', from=''}
2017-10-19 17:48:54.724 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== ====準備修改數據====
2017-10-19 17:48:54.725 DEBUG 2736 --- [nio-8385-exec-1] c.i.cloud.mapper.IUserMapper.updateUser : ==> Preparing: update user set userName=?,name=?,age=?,balance=? where id=?
2017-10-19 17:48:54.725 DEBUG 2736 --- [nio-8385-exec-1] c.i.cloud.mapper.IUserMapper.updateUser : ==> Parameters: user66(String), user66(String), 2000(Integer), 2000(String), 147(Long)
2017-10-19 17:48:54.738 DEBUG 2736 --- [nio-8385-exec-1] c.i.cloud.mapper.IUserMapper.updateUser : <== Updates: 1
2017-10-19 17:48:54.747 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== ==== 修改數據 == 成功 ==
2017-10-19 17:48:54.747 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== ====修改後再次查詢數據
2017-10-19 17:48:54.747 DEBUG 2736 --- [nio-8385-exec-1] c.i.c.mapper.IUserMapper.findUserById : ==> Preparing: select * from user where id = ?
2017-10-19 17:48:54.747 DEBUG 2736 --- [nio-8385-exec-1] c.i.c.mapper.IUserMapper.findUserById : ==> Parameters: 147(Long)
2017-10-19 17:48:54.747 DEBUG 2736 --- [nio-8385-exec-1] c.i.c.mapper.IUserMapper.findUserById : <== Total: 1
2017-10-19 17:48:54.747 INFO 2736 --- [nio-8385-exec-1] erMysqlMybatisMapperXmlEhCacheController : =========== ====修改後再次查詢數據結果: User{id=147, username='user66', name='user66', age=2000, balance='2000', from=''}
總結:可以看出查詢過一次後,就不會再查詢數據庫了,所以第二次、第三次都會去查找緩存的數據;
****************************************************************************************/
/****************************************************************************************
Ehcache 相關資料:
diskStore:爲緩存路徑,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,最近最少使用的,緩存的元素有一個時間戳,當緩存容量滿了,而又需要騰出地方來緩存新的元素的時候,那麼現有緩存元素中時間戳離當前時間最遠的元素將被清出緩存。
一般情況下,我們在Sercive層進行對緩存的操作。先介紹 Ehcache 在 Spring 中的註解:在支持 Spring Cache 的環境下,
* @Cacheable : Spring在每次執行前都會檢查Cache中是否存在相同key的緩存元素,如果存在就不再執行該方法,而是直接從緩存中獲取結果進行返回,否則纔會執行並將返回結果存入指定的緩存中。
* @CacheEvict : 清除緩存。
* @CachePut : @CachePut也可以聲明一個方法支持緩存功能。使用@CachePut標註的方法在執行前不會去檢查緩存中是否存在之前執行過的結果,而是每次都會執行該方法,並將執行結果以鍵值對的形式存入指定的緩存中。
* 這三個方法中都有兩個主要的屬性:value 指的是 ehcache.xml 中的緩存策略空間;key 指的是緩存的標識,同時可以用 # 來引用參數。
****************************************************************************************/
四、下載地址
https://gitee.com/ylimhhmily/SpringCloudTutorial.git
SpringCloudTutorial交流QQ羣: 235322432
SpringCloudTutorial交流微信羣: 微信溝通羣二維碼圖片鏈接
歡迎關注,您的肯定是對我最大的支持!!!