淺析SpringBoot整合Mybatis如何實(shí)現(xiàn)二級緩存
mybatis 原生
二級緩存,是指多個Sqlsession之間共享數(shù)據(jù),但是也可以使用Redis這樣的緩存作為存儲點(diǎn)。 但是不支持mybatisplus 里的方法。
處理類,用于攔截mapper緩存。
import org.apache.ibatis.cache.Cache;
public record MybatisRedisCache(String id) implements Cache {
private static final StringRedisTemplate redisTemplate;
static {
redisTemplate = SpringUtil.getBean(StringRedisTemplate.class);
}
@Override
public String getId() {
return id;
}
@Override
public void putObject(Object key, Object value) {
if (value != null) {
redisTemplate.opsForValue().set(getKey(key), JSONUtil.toJsonStr(value));
}
}
@Override
public Object getObject(Object key) {
String string = redisTemplate.opsForValue().get(getKey(key));
if (string == null) return null;
return isArray(string);
}
@Override
public Object removeObject(Object key) {
String redisKey = getKey(key);
Object value = redisTemplate.opsForValue().get(redisKey);
redisTemplate.delete(redisKey);
return value;
}
@Override
public void clear() {
redisTemplate.delete(Objects.requireNonNull(redisTemplate.keys(getKey("*"))));
}
@Override
public int getSize() {
return 0;
}
private String getKey(Object key) {
return id + ":" + key.hashCode();
}
public Object isArray(String str) {
JSON json = JSONUtil.parse(str);
if (json instanceof cn.hutool.json.JSONArray) {
// 是數(shù)組
return JSONUtil.toList((cn.hutool.json.JSONArray) json, Object.class);
}
if (json instanceof cn.hutool.json.JSONObject) {
// 是對象
return JSONUtil.toBean((cn.hutool.json.JSONObject) json, Object.class);
}
throw new RuntimeException("緩存數(shù)據(jù)格式錯誤");
}
}mapper xml
一定要加 cache-ref 才能進(jìn)行二級緩存
<mapper namespace="com.example.dao.UserMapper">
<cache-ref namespace="com.example.dao.UserMapper"/>
<select id="selectAll" resultType="com.example.Demo">
select *
from demo
</select>
</mapper>
配置 CacheNamespace 使用就可以了
@CacheNamespace(implementation = MybatisRedisCache.class)
public interface UserMapper extends BaseMapper<Demo> {
List<Demo> selectAll();
}
Spring Cache
@Configuration
@EnableCaching
public class RedisCacheConfig {
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)) // 默認(rèn)緩存 10 分鐘
.disableCachingNullValues() // 避免存入控制
.serializeValuesWith( // 設(shè)置序列化
RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())
);
// 返回
return RedisCacheManager.builder(factory).cacheDefaults(config).build();
}
}
Cacheable 緩存、CacheEvict 刪除,拼接 key
@Service
public class DemoService extends ServiceImpl<UserMapper, Demo> {
@Cacheable(value = "user:cache", key = "#id")
public Demo getOne(Long id) {
return getById(id);
}
@Caching(evict = {
@CacheEvict(value = "user:cache", key = "#id"),
@CacheEvict(value = "user:all", allEntries = true)}
)
public void deleteById(String id) {
removeById(id);
}
// 更新數(shù)據(jù)后刷新緩存
@Caching(
put = {@CachePut(value = "user:cache", key = "#demo.id", unless = "#result == null")},
evict = {@CacheEvict(value = "user:all", allEntries = true)}
)
public void updateUser(Demo demo) {
updateById(demo);
}
@Cacheable(value = "user:all")
public List<Demo> listDemo() {
return list();
}
}到此這篇關(guān)于淺析SpringBoot整合Mybatis如何實(shí)現(xiàn)二級緩存的文章就介紹到這了,更多相關(guān)SpringBoot Mybatis二級緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java HttpClient傳輸json格式的參數(shù)實(shí)例講解
這篇文章主要介紹了java HttpClient傳輸json格式的參數(shù)實(shí)例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
java web實(shí)現(xiàn)網(wǎng)上手機(jī)銷售系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java web實(shí)現(xiàn)網(wǎng)上手機(jī)銷售系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
java程序員自己的圖片轉(zhuǎn)文字OCR識圖工具分享
這篇文章主要介紹了java程序員自己的圖片轉(zhuǎn)文字OCR識圖工具,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11
javax.validation.constraints.NotNull找不到的問題及解決
文章主要介紹了Java Bean驗(yàn)證注解的使用,包括`@NotNull`、`@AssertFalse`、`@DecimalMax`、`@Pattern`等,并提供了每個注解的使用范例2026-02-02
SpringMVC中的@RequestMapping注解的使用詳細(xì)教程
@RequestMapping注解的作用就是將請求和處理請求的控制器方法關(guān)聯(lián)起來,建立映射關(guān)系,本文主要來和大家詳細(xì)講講它的具體使用,感興趣的可以了解一下2023-07-07
Java進(jìn)行日期解析與格式化的實(shí)現(xiàn)代碼
使用 Java 搭配 Apache Commons Lang3 和 Natty 庫,可以實(shí)現(xiàn)靈活高效的日期解析與格式化,本文將通過相關(guān)示例為大家講講具體的實(shí)踐操作,需要的可以了解下2025-05-05
Spring @CrossOrigin 注解原理實(shí)現(xiàn)
這篇文章主要介紹了Spring @CrossOrigin 注解原理實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07

