redis之mybatis快取(單機+叢集)
1. 快取的概念。
1.1. 什麼是快取(cache)
1) cache是高速緩衝儲存器,主要解決頻繁使用的資料快速訪問的問題。
2) 如果兩個硬體或者軟體之間的速度存在較大差異,主要使用快取協調兩者的速度差異。
1.2. 快取的分類
1) 作業系統磁碟快取:減少磁碟機械操作。
2) 資料庫快取:減少應用程式對資料庫伺服器的IO操作。
3) web伺服器快取:減輕web伺服器的壓力。
4) 瀏覽器快取:訪問速度快,提升使用者體驗度,減輕網站壓力。
2. redis(單機版)實現mybatis的二級快取
2.1. 環境準備
使用maven搭建一套ssm框架,並建立測試類查詢emp表。測試程式碼如下:
/**
* 不使用快取的查詢時間
*/
public static void main(String[] args) {
ApplicationContext ac =newClassPathXmlApplicationContext("applicationContext.xml");
EmpMapper empMapper=(EmpMapper) ac.getBean("empMapper");
Long begin=System.currentTimeMillis();
empMapper.findAllEmp();
Long end=System.currentTimeMillis
System.out.println("花費時間:"+(end-begin));
}
結果截圖:
2.2. 配置mybais的二級快取
1) 修改配置檔案mapper.xml
加上<cache eviction="LRU" type="com.aaa.util.RedisCache" />,<!-- eviction:定義快取的移除機制;預設是LRU(least recently userd,最近最少使用),還有FIFO(first in first out,先進先出) -->
2) 修改配置檔案applicationContext.xml,開啟mabatis快取
<!-- 開啟快取支援 -->
<property name="configurationProperties">
<props>
<prop key="cacheEnabled">true</prop>
<!-- 查詢時,關閉關聯物件即時載入以提高效能 -->
<prop key="lazyLoadingEnabled">false</prop>
<!-- 設定關聯物件載入的形態,此處為按需載入欄位(載入欄位由SQL指定),不會載入關聯表的所有欄位,以提高效能 -->
<prop key="aggressiveLazyLoading">true</prop>
<!-- 對於未知的SQL查詢,允許返回不同的結果集以達到通用的效果 -->
<prop key="multipleResultSetsEnabled">true</prop>
<!-- 允許使用列標籤代替列名 -->
<prop key="useColumnLabel">true</prop>
<!-- 允許使用自定義的主鍵值(比如由程式生成的UUID 32位編碼作為鍵值),資料表的PK生成策略將被覆蓋 -->
<prop key="useGeneratedKeys">true</prop>
<!-- 給予被巢狀的resultMap以欄位-屬性的對映支援 -->
<prop key="autoMappingBehavior">FULL</prop>
<!-- 對於批量更新操作快取SQL以提高效能 -->
<prop key="defaultExecutorType">BATCH</prop>
<!-- 資料庫超過25000秒仍未響應則超時 -->
<prop key="defaultStatementTimeout">25000</prop>
</props>
</property>
3) 新增配置檔案spring-redis.xml
<!-- redis連線池配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="2000" />
<property name="maxTotal" value="20000" />
<property name="minEvictableIdleTimeMillis" value="300000"></property>
<property name="numTestsPerEvictionRun" value="3"></property>
<property name="timeBetweenEvictionRunsMillis" value="60000"></property>
<property name="maxWaitMillis" value="20000" />
<property name="testOnBorrow" value="false" />
</bean>
<!-- Spring-redis連線池管理工廠 -->
<bean id="jedisConnectionFactory"class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="192.168.153.164" />
<property name="port" value="6379" />
<property name="poolConfig" ref="poolConfig" />
</bean>
<!-- 使用中間類解決RedisCache.jedisConnectionFactory的靜態注入,從而使MyBatis實現第三方快取 -->
<bean id="redisCache" class="com.aaa.util.RedisCacheTransfer">
<property name="jedisConnectionFactory" ref="jedisConnectionFactory"></property>
</bean>
4) 建立mybatis cache介面的實現類RedisCache
/**
* @author chenjian
* @description 使用第三方快取伺服器,處理二級快取
* @company AAA軟體
* 2017-6-29下午2:16:56
*/
public class RedisCache implements Cache {
private static JedisConnectionFactory jedisConnectionFactory;
private final String id;
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public RedisCache(final String id){
if (id == null) {
throw new IllegalArgumentException("cache instances require an ID");
}
this.id = id;
}
/**
*
* @description: 清空redis快取
* @author
* @param
* @return
*/
@Override
public void clear() {
RedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
connection.flushDb();//清空redis中的資料
connection.flushAll();//#移除所有key從所有庫中
} catch (Exception e) {
e.printStackTrace();
}finally{
if (connection != null) {
connection.close();
}
}
}
@Override
public String getId() {
return this.id;
}
/**
*
* @description: 根據key獲取redis快取中的值
* @author
* @param
* @return
*/
@Override
public Object getObject(Object key) {
System.out.println("--------------------------------key:["+key+"]");
Object result = null;
RedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
//serializer.serialize(key)將key序列化
//connection.get(serializer.serialize(key))根據key去redis中獲取value
//serializer.deserialize將value反序列化
result = serializer.deserialize(connection.get(serializer.serialize(key)));
} catch (Exception e) {
e.printStackTrace();
}finally{
if (connection != null) {
connection.close();
}
}
return result;
}
@Override
public ReadWriteLock getReadWriteLock() {
return this.readWriteLock;
}
@Override
public int getSize() {
int result = 0;
RedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
result = Integer.valueOf(connection.dbSize().toString());
} catch (Exception e) {
e.printStackTrace();
}finally{
if (connection != null) {
connection.close();
}
}
return result;
}
/**
*
* @description: 將資料儲存到redis快取
* @author
* @param
* @return
*/
@Override
public void putObject(Object key, Object value) {
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>key:"+key);
RedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
System.out.println("**"+serializer.serialize(key));
//serializer.serialize(value)將value序列化,serializer.serialize(key)將key序列化
connection.set(serializer.serialize(key), serializer.serialize(value));
} catch (Exception e) {
e.printStackTrace();
}finally{
if (connection != null) {
connection.close();
}
}
}
/**
*
* @description: 根據key清除redis快取中對應 的值
* @author
* @param
* @return
*/
@Override
public Object removeObject(Object key) {
RedisConnection connection = null;
Object result = null;
try {
connection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
result = connection.expireAt(serializer.serialize(key), 0);
} catch (Exception e) {
e.printStackTrace();
}finally{
if (connection != null) {
connection.close();
}
}
return result;
}
public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCache.jedisConnectionFactory = jedisConnectionFactory;
}
5) 建立中間類,解決RedisCache.jedisConnectionFactory的靜態注入,從而使MyBatis實現第三方快取
/**
* @author TeacherChen
* @description 建立中間類RedisCacheTransfer,完成RedisCache.jedisConnectionFactory的靜態注入
* @company AAA軟體
* 2018-1-12上午8:46:18
*/
public class RedisCacheTransfer {
public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
}
}
6) 測試類
/**
* 使用快取的查詢時間
*/
public static void main(String[] args) {
ApplicationContext ac =newClassPathXmlApplicationContext("applicationContext.xml","spring-redis.xml");
EmpMapper empMapper=(EmpMapper) ac.getBean("empMapper");
Long begin=System.currentTimeMillis();
List<Emp> empList = empMapper.findAllEmp();
System.out.println("員工數:"+empList.size());
Long end=System.currentTimeMillis();
System.out.println("花費時間:"+(end-begin));
}
7) 測試效果
第一次查詢
第二次查詢
3. redis(叢集版)實現mybatis的二級快取
3.1. 修改配置檔案spring-redis.xml
<!-- redis叢集配置 -->
<bean id="redisClusterConfiguration"class="org.springframework.data.redis.connection.RedisClusterConfiguration">
<property name="maxRedirects" value="3"></property>
<property name="clusterNodes">
<set>
<bean class="org.springframework.data.redis.connection.RedisClusterNode">
<constructor-arg index="0" value="192.168.153.164"></constructor-arg>
<constructor-arg index="1" value="7001"></constructor-arg>
</bean>
<bean class="org.springframework.data.redis.connection.RedisClusterNode">
<constructor-arg index="0" value="192.168.153.164"></constructor-arg>
<constructor-arg index="1" value="7002"></constructor-arg>
</bean>
<bean class="org.springframework.data.redis.connection.RedisClusterNode">
<constructor-arg index="0" value="192.168.153.164"></constructor-arg>
<constructor-arg index="1" value="7003"></constructor-arg>
</bean>
<bean class="org.springframework.data.redis.connection.RedisClusterNode">
<constructor-arg index="0" value="192.168.153.164"></constructor-arg>
<constructor-arg index="1" value="7004"></constructor-arg>
</bean>
<bean class="org.springframework.data.redis.connection.RedisClusterNode">
<constructor-arg index="0" value="192.168.153.164"></constructor-arg>
<constructor-arg index="1" value="7005"></constructor-arg>
</bean>
<bean class="org.springframework.data.redis.connection.RedisClusterNode">
<constructor-arg index="0" value="192.168.153.164"></constructor-arg>
<constructor-arg index="1" value="7006"></constructor-arg>
</bean>
</set>
</property>
</bean>
<!-- Spring-redis連線池管理工廠 -->
<bean id="jedisConnectionFactory"class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<constructor-arg name="poolConfig" ref="poolConfig"/>
<constructor-arg name="clusterConfig" ref="redisClusterConfiguration"/>
</bean>
3.2. 測試效果
1) 啟動redis叢集
redis-server /usr/local/redis_cluster/7001/redis.confredis-server /usr/local/redis_cluster/7002/redis.confredis-server /usr/local/redis_cluster/7003/redis.confredis-server /usr/local/redis_cluster/7004/redis.confredis-server /usr/local/redis_cluster/7005/redis.confredis-server /usr/local/redis_cluster/7006/redis.conf
2) 清空叢集中的所有key,要在主節點上操作
使用FLUSHALL命令在所有的主節點
3) 第一次查詢
4) 第二次查詢