mybatis使用redis缓存两种方式

2024-05-09 12:36

本文主要是介绍mybatis使用redis缓存两种方式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、注入

@EnableAsync //开启异步
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class RuoYiApplication
{public static void main(String[] args){// System.setProperty("spring.devtools.restart.enabled", "false");SpringApplication.run(RuoYiApplication.class, args);System.out.println("(♥◠‿◠)ノ゙  若依启动成功   ლ(´ڡ`ლ)゙  \n" +" .-------.       ____     __        \n" +" |  _ _   \\      \\   \\   /  /    \n" +" | ( ' )  |       \\  _. /  '       \n" +" |(_ o _) /        _( )_ .'         \n" +" | (_,_).' __  ___(_ o _)'          \n" +" |  |\\ \\  |  ||   |(_,_)'         \n" +" |  | \\ `'   /|   `-'  /           \n" +" |  |  \\    /  \\      /           \n" +" ''-'   `'-'    `-..-'              ");}@Autowiredpublic void setRedisTemplate(RedisTemplate redisTemplate) {MybatisRedisCache.setRedisTemplate(redisTemplate);}
}
package com.ruoyi.util.cache;import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;public class MybatisRedisCache implements Cache {private static final Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class);private static RedisTemplate<String, Object> redisTemplate;private final String id;/*** The {@code ReadWriteLock}.*/private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();@Overridepublic ReadWriteLock getReadWriteLock() {return this.readWriteLock;}public static void setRedisTemplate(RedisTemplate redisTemplate) {MybatisRedisCache.redisTemplate = redisTemplate;}public MybatisRedisCache() {this.id = null;}public MybatisRedisCache(final String id) {if (id == null) {throw new IllegalArgumentException("Cache instances require an ID");}logger.debug("MybatisRedisCache:id=" + id);this.id = id;}@Overridepublic String getId() {return this.id;}@Overridepublic void putObject(Object key, Object value) {try {logger.info(">>>>>>>>>>>>>>>>>>>>>>>>putObject: key=" + key + ",value=" + value);if (null != value) {redisTemplate.opsForValue().set(key.toString(), value, 60, TimeUnit.SECONDS);}} catch (Exception e) {e.printStackTrace();logger.error("redis保存数据异常!");}}@Overridepublic Object getObject(Object key) {try {logger.info(">>>>>>>>>>>>>>>>>>>>>>>>getObject: key=" + key);if (null != key) {return redisTemplate.opsForValue().get(key.toString());}} catch (Exception e) {e.printStackTrace();logger.error("redis获取数据异常!");}return null;}@Overridepublic Object removeObject(Object key) {try {if (null != key) {return redisTemplate.expire(key.toString(), 1, TimeUnit.DAYS);}} catch (Exception e) {e.printStackTrace();logger.error("redis获取数据异常!");}return null;}@Overridepublic void clear() {Long size = redisTemplate.execute(new RedisCallback<Long>() {@Overridepublic Long doInRedis(RedisConnection redisConnection) throws DataAccessException {Long size = redisConnection.dbSize();//连接清除数据redisConnection.flushDb();redisConnection.flushAll();return size;}});logger.info(">>>>>>>>>>>>>>>>>>>>>>>>clear: 清除了" + size + "个对象");}@Overridepublic int getSize() {Long size = redisTemplate.execute(new RedisCallback<Long>() {@Overridepublic Long doInRedis(RedisConnection connection)throws DataAccessException {return connection.dbSize();}});return size.intValue();}
}

2、bean工具引入

package com.ruoyi.util;import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.util.CollectionUtils;import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;/*** @class: MybatisRedisCache*/
@Slf4j
public class MybatisRedisCache implements Cache {// 读写锁private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);//这里使用了redis缓存,使用springboot自动注入private RedisTemplate<String, Object> redisTemplate;private String id;public MybatisRedisCache(final String id) {if (id == null) {throw new IllegalArgumentException("Cache instances require an ID");}this.id = id;}@Overridepublic String getId() {return this.id;}@Overridepublic void putObject(Object key, Object value) {if (redisTemplate == null) {//由于启动期间注入失败,只能运行期间注入,这段代码可以删除redisTemplate = (RedisTemplate<String, Object>) SpringUtil.getBean("redisTemplate");}if (value != null) {redisTemplate.opsForValue().set(key.toString(), value);}}@Overridepublic Object getObject(Object key) {if (redisTemplate == null) {//由于启动期间注入失败,只能运行期间注入,这段代码可以删除redisTemplate = (RedisTemplate<String, Object>) SpringUtil.getBean("redisTemplate");}try {if (key != null) {return redisTemplate.opsForValue().get(key.toString());}} catch (Exception e) {e.printStackTrace();log.error("缓存出错 ");}return null;}@Overridepublic Object removeObject(Object key) {if (redisTemplate == null) {//由于启动期间注入失败,只能运行期间注入,这段代码可以删除redisTemplate = (RedisTemplate<String, Object>) SpringUtil.getBean("redisTemplate");}if (key != null) {redisTemplate.delete(key.toString());}return null;}@Overridepublic void clear() {log.debug("清空缓存");if (redisTemplate == null) {redisTemplate = (RedisTemplate<String, Object>) SpringUtil.getBean("redisTemplate");}try {Set<String> keys = scan(this.id);if (!CollectionUtils.isEmpty(keys)) {redisTemplate.delete(keys);}} catch (Exception e) {log.error("清空缓存", e);}}public Set<String> scan(String matchKey) {if (redisTemplate == null) {redisTemplate = (RedisTemplate<String, Object>) SpringUtil.getBean("redisTemplate");}Set<String> keys = redisTemplate.execute((RedisCallback<Set<String>>) connection -> {Set<String> keysTmp = new HashSet<>();Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match("*" + matchKey + "*").count(1000).build());while (cursor.hasNext()) {keysTmp.add(new String(cursor.next()));}return keysTmp;});return keys;}@Overridepublic int getSize() {if (redisTemplate == null) {//由于启动期间注入失败,只能运行期间注入,这段代码可以删除redisTemplate = (RedisTemplate<String, Object>) SpringUtil.getBean("redisTemplate");}Long size = redisTemplate.execute((RedisCallback<Long>) RedisServerCommands::dbSize);return size.intValue();}@Overridepublic ReadWriteLock getReadWriteLock() {return this.readWriteLock;}}

这篇关于mybatis使用redis缓存两种方式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/973432

相关文章

1、swift学习-字典的基本使用

1、创建一个字典          var dic:Dictionary<String,String> = ["三国演艺":"罗贯中","水浒传":"施耐庵","红楼梦":"曹雪芹","西游记":"吴承恩"]; 2、打印字典的值     println(dic);     结果如下图:      3、访问字典中某一个键值     var

Swift5 导航栏的使用 2022年11月更新

Swift 导航栏的使用 一、基本使用 1.1 创建导航栏 在AppDelegate 如下方法中添加创建导航栏的代码: func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> B

Swift5 Tabbar的使用

Swift Tabbar的使用 一、基本使用 1.1 创建Tabbar import UIKitclass RootTabbar: UITabBarController {override func viewDidLoad() {super.viewDidLoad()let nav1 = UINavigationController(rootViewController: ControlMa

Swift 字典数组元组的使用 - 2022年11月更新

Swift 字典数组元组的使用 一、字典 Swift 字典用来存储无序的相同类型数据的集合,Swift 字典会强制检测元素的类型,如果类型不同则会报错。Swift 字典的key没有类型限制可以是整型或字符串,但必须是唯一的。let 修饰的字典为不可变字典,var 修饰的字典为可变字典。 1.1 字典的创建和取值 let dict = ["name":"张三","age":"20","add

iOS Face++人脸识别SDK的使用

前言 1、注册一个Face++的帐号,创建应用,获取APPID和APPKEY; 2、下载人脸识别的SDK到本地; 一、将SDK导入工程 1、将下载的SDK解压,将FaceappSDK文件夹拖入工程中 2、在工程设置文件中的Build Settings内,将”Objective-C Automatic Reference Counting”设置为NO 3、Face++的SDK比较

iOS 环信3.2集成 (一)基本使用

前言 1、本教程对应环信即时聊天 iOS SDK V3.2.0 (2016-10-15) 2、请自行注册好环信APP_ID和APP_KEY 3、请自行下载好环信即时聊天SDK对应的版本(easemob.com/download”>iOS SDK V3.2.0) 一、集成环信SDK 1、导入SDK 下载SDK到本地,进行解压,包含以下几个文件。 如果你的项目中需要用到语音电话和语音

3.1 Activity的基本使用

一、基本使用 1、Activity的开启与关闭 开启一个Activity Intent intent = new Intent(MainActivity.this,Main2Activity.class);startActivity(intent); 关闭一个Activity finish(); 2、Activity之间数据传递 (1) 方法一 A 界面传值代码如下: I

iOS Masonry(约束)的基本使用

一、简介 Masonry是一个轻量级的布局框架 拥有自己的描述语法 采用更优雅的链式语法封装自动布局 简洁明了 并具有高可读性 而且同时支持 iOS 和 Max OS X。 Masonry支持的一些属性 //左侧@property (nonatomic, strong, readonly) MASConstraint *left;//上侧@property (nonatomic, st

2.14 ProgressDialog 进度条对话框的使用

一、布局文件 <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_paren

2.13 Notification(通知)的使用

一、布局文件 activity_main.xml 添加代码: <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools" android