SpringBoot+Mybatis項(xiàng)目使用Redis做Mybatis的二級(jí)緩存的方法
介紹
使用mybatis時(shí)可以使用二級(jí)緩存提高查詢(xún)速度,進(jìn)而改善用戶(hù)體驗(yàn)。
使用redis做mybatis的二級(jí)緩存可是內(nèi)存可控<如將單獨(dú)的服務(wù)器部署出來(lái)用于二級(jí)緩存>,管理方便。
1.在pom.xml文件中引入redis依賴(lài)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.在application.properties配置文件中進(jìn)行redis的配置
## Redis spring.redis.database=0 spring.redis.host=172.16.3.123 spring.redis.port=6379 spring.redis.password= spring.redis.pool.max-active=8 spring.redis.pool.max-wait=-1 spring.redis.pool.max-idle=8 spring.redis.pool.min-idle=0 spring.redis.timeout=0
3.創(chuàng)建cache包,然后創(chuàng)建兩個(gè)類(lèi),一個(gè)ApplicationContextHolder實(shí)現(xiàn)ApplicationContextAware接口,具體內(nèi)容如下
package com.ruijie.SpringBootandRedis.cache;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
applicationContext = ctx;
}
/**
* Get application context from everywhere
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* Get bean by class
*
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
/**
* Get bean by class name
*
* @param name
* @param <T>
* @return
*/
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
}
4.創(chuàng)建RedisCache類(lèi)實(shí)現(xiàn)Cache接口,具體內(nèi)容如下:
package com.ruijie.SpringBootandRedis.cache;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class RedisCache implements Cache {
private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final String id; // cache instance id
private RedisTemplate redisTemplate;
private static final long EXPIRE_TIME_IN_MINUTES = 30; // redis過(guò)期時(shí)間
public RedisCache(String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
this.id = id;
}
@Override
public String getId() {
return id;
}
/**
* Put query result to redis
*
* @param key
* @param value
*/
@Override
public void putObject(Object key, Object value) {
try {
RedisTemplate redisTemplate = getRedisTemplate();
ValueOperations opsForValue = redisTemplate.opsForValue();
opsForValue.set(key, value, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES);
logger.debug("Put query result to redis");
}
catch (Throwable t) {
logger.error("Redis put failed", t);
}
}
/**
* Get cached query result from redis
*
* @param key
* @return
*/
@Override
public Object getObject(Object key) {
try {
RedisTemplate redisTemplate = getRedisTemplate();
ValueOperations opsForValue = redisTemplate.opsForValue();
logger.debug("Get cached query result from redis");
System.out.println("****"+opsForValue.get(key).toString());
return opsForValue.get(key);
}
catch (Throwable t) {
logger.error("Redis get failed, fail over to db", t);
return null;
}
}
/**
* Remove cached query result from redis
*
* @param key
* @return
*/
@Override
@SuppressWarnings("unchecked")
public Object removeObject(Object key) {
try {
RedisTemplate redisTemplate = getRedisTemplate();
redisTemplate.delete(key);
logger.debug("Remove cached query result from redis");
}
catch (Throwable t) {
logger.error("Redis remove failed", t);
}
return null;
}
/**
* Clears this cache instance
*/
@Override
public void clear() {
RedisTemplate redisTemplate = getRedisTemplate();
redisTemplate.execute((RedisCallback) connection -> {
connection.flushDb();
return null;
});
logger.debug("Clear all the cached query result from redis");
}
/**
* This method is not used
*
* @return
*/
@Override
public int getSize() {
return 0;
}
@Override
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
}
private RedisTemplate getRedisTemplate() {
if (redisTemplate == null) {
redisTemplate = ApplicationContextHolder.getBean("redisTemplate");
}
return redisTemplate;
}
}
5.實(shí)體類(lèi)中要實(shí)現(xiàn)Serializable接口,并且要聲明序列號(hào)
private static final long serialVersionUID = -2566441764189220519L;
6.開(kāi)啟Mybatis的二級(jí)緩存
在pom.xml配置文件中配置
mybatis.configuration.cache-enabled=true
在mapper接口中加入
@CacheNamespace(implementation=(com.demo.testdemo.cache.RedisCache.class))
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring MVC的參數(shù)綁定和返回值問(wèn)題
這篇文章主要介紹了Spring MVC的參數(shù)綁定和返回值問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-02-02
SpringBoot整合ShardingSphere5.x實(shí)現(xiàn)數(shù)據(jù)加解密功能(最新推薦)
這篇文章主要介紹了SpringBoot整合ShardingSphere5.x實(shí)現(xiàn)數(shù)據(jù)加解密功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06
java程序員如何編寫(xiě)更好的單元測(cè)試的7個(gè)技巧
測(cè)試是開(kāi)發(fā)的一個(gè)非常重要的方面,可以在很大程度上決定一個(gè)應(yīng)用程序的命運(yùn)。良好的測(cè)試可以在早期捕獲導(dǎo)致應(yīng)用程序崩潰的問(wèn)題,但較差的測(cè)試往往總是導(dǎo)致故障和停機(jī)。本文主要介紹java程序員編寫(xiě)更好的單元測(cè)試的7個(gè)技巧。下面跟著小編一起來(lái)看下吧2017-03-03
又又叕出BUG啦!理智分析Java NIO的ByteBuffer到底有多難用
網(wǎng)絡(luò)數(shù)據(jù)的基本單位永遠(yuǎn)是byte,Java NIO提供ByteBuffer作為字節(jié)的容器,但該類(lèi)過(guò)于復(fù)雜,有點(diǎn)難用.本篇文章就帶大家簡(jiǎn)單了解一下 ,需要的朋友可以參考下2021-06-06
Springcloud RestTemplate服務(wù)調(diào)用代碼實(shí)例
這篇文章主要介紹了Springcloud RestTemplate服務(wù)調(diào)用代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
java網(wǎng)絡(luò)編程之socket網(wǎng)絡(luò)編程示例(服務(wù)器端/客戶(hù)端)
這篇文章主要介紹了java socket網(wǎng)絡(luò)編程的示例,分為服務(wù)器端和客戶(hù)端,大家參考使用吧2014-01-01
SpringBoot MyBatis簡(jiǎn)單快速入門(mén)例子
MyBatis 是一款優(yōu)秀的持久層框架,它支持自定義 SQL、存儲(chǔ)過(guò)程以及高級(jí)映射。這篇文章主要介紹了SpringBoot MyBatis快速入門(mén)-簡(jiǎn)單例子,需要的朋友可以參考下2021-07-07
帶你了解Java數(shù)據(jù)結(jié)構(gòu)和算法之無(wú)權(quán)無(wú)向圖
這篇文章主要為大家介紹了Java數(shù)據(jù)結(jié)構(gòu)和算法之無(wú)權(quán)無(wú)向圖?,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-01-01

