1. 程式人生 > >springboot整合mybatis,mysql做資料庫儲存,redis做快取

springboot整合mybatis,mysql做資料庫儲存,redis做快取

redis應用的場景

通過快取來減少對關係型資料庫的查詢次數,減輕資料庫壓力。在執行DAO類的select***(), query***()方法時,先從Redis中查詢有沒有快取資料,如果有則直接從Redis拿到結果,如果沒有再向資料庫發起查詢請求取資料。


springboot已經集成了redis快取,只需要在pom.xml中載入redis,然後通過註解即可完成配置。

首先在配置類中加上 @EnableCaching 註解


然後在DAO類加上@CacheConfig 註解

類中的對資料庫操作的函式按功能加上 @CachePut @CacheEvict @Cacheable

@CachePut 是將資料加入到redis快取中


@Cacheable 在獲取資料的時候會先查詢快取,如果快取中存在,則不執行查詢資料庫的方法,如果不存在則查詢資料庫,並加入到快取中。

@CacheEvict 一般註解到刪除資料的操作上,會將一條或多條資料從快取中刪除。

這三個方法都有value 和 key屬性

value指的是快取的名稱,不能為空。也可以在類@CacheConfig註解上指定value,則後面的方法的註解value可省略且value值與類註解的value相同。

key是快取的鍵,預設為空,既表示使用方法的引數型別及引數值作為key。可通過key = "#p0",p0為方法的第一個引數,p1為第二個,也可直接 #引數的名字。

還有一個註解為@Caching  用於組合將多個註解註解到一個方法上。

具體程式碼:

package com.example.demo.dao;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.example.demo.entity.Diary;
import com.example.demo.entity.User;
import com.example.demo.map.DiaryMapper;
import com.example.demo.map.UserMapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@CacheConfig(cacheNames="userCache") // 本類內方法指定使用快取時,預設的名稱就是userCache
public class UserDAOImpl implements UserDAO{
	
	String resource = null;
	InputStream is = null;
	SqlSessionFactory sqlSessionFactory = null;
	SqlSession sqlSession = null;
	
	public UserDAOImpl() throws IOException {
		resource = "sqlMapConfig.xml";
		is = Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
		sqlSession = sqlSessionFactory.openSession();
	}
	//檢查註冊時使用者名稱是否可用
	public boolean checkUsername(String username) {
		boolean flag = true;
		UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
		String name = userMapper.selectPwdByUsername(username);
		sqlSession.commit();
		if (name==username) {
			flag = true;
		}
		return flag;
	}
	//登入時密碼驗證
	@Cacheable()
	public boolean checkPass(String username,String pwd){
		boolean flag = false;
		UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
		String pass = userMapper.selectPwdByUsername(username);
		System.out.println("查詢資料庫");
		sqlSession.commit();
		if(pass != null){
			if (pass.equals(pwd)) {
				flag = true;
			}
			
		}else{
			
		}
		return flag;
	}
	//註冊
	@CachePut()
	public void register(String username,String userpwd,String email,String question,String answer,String photo){
		User user = new User();
		user.setUsername(username);
		user.setPwd(userpwd);
		user.setEmail(email);
		user.setQuestion(question);
		user.setAnswer(answer);
		user.setImage(photo);
		UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
		try {
			int flag = userMapper.insertUser(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sqlSession.commit();

	}
	//分享
	@CachePut(key = "#P1")
	public void share(String username,String title,String content){
		String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
		System.out.println(time);
		Diary diary = new Diary();
		diary.setTitle(title);
		diary.setContent(content);
		diary.setWriteTime(time);
		//User user = new User();
		diary.setUsername(username);
		DiaryMapper diaryMapper=sqlSession.getMapper(DiaryMapper.class);
		try {
			int flag = diaryMapper.insertDiary(diary);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sqlSession.commit();
	}

	//@Cacheable() // @Cacheable 會先查詢快取,如果快取中存在,則不執行方法
	public User selectUser(String username){
		User user = null;
		System.out.println(username);
		UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
		user = userMapper.selectUser(username);
		sqlSession.commit();
		return user;
	}
	@Cacheable(key = "getMethodName()") // @Cacheable 會先查詢快取,如果快取中存在,則不執行方法
    public List<Diary> seeShare() {
		List<Diary> list = new LinkedList<Diary>();
		DiaryMapper diaryMapper = sqlSession.getMapper(DiaryMapper.class);
		list = diaryMapper.selectShare();
		sqlSession.commit();
		return list;
    }
}

當執行時會將資料加入到快取,在redis視覺化工具中檢視資料如下


顯示的資料就是redis存入到記憶體中的二進位制格式的資料,然後用十六進位制顯示了出來。

get一下也會顯示這些資料


注意:在快取物件是要讓物件類實現Serializable介面,將物件序列化後再儲存到記憶體中,取出來的時候redis會自動反序列化再顯示出來。

相關推薦

springboot整合mybatismysql資料庫儲存redis快取

redis應用的場景通過快取來減少對關係型資料庫的查詢次數,減輕資料庫壓力。在執行DAO類的select***(), query***()方法時,先從Redis中查詢有沒有快取資料,如果有則直接從Redis拿到結果,如果沒有再向資料庫發起查詢請求取資料。springboot已

SpringBoot】——SpringBoot 整合mybatis-plus 單資料來源 & 多資料來源附原始碼

相信大家已經看了不少的教程了,所以在此我不在贅述。。。。。。 遇到的坑,在專案中readme.md 中有描述。具體下載下來配置比較詳細,初始化sql ,單元測試。。。檢視流程即可。 demo非常簡單,下載下來參考 readme.md 修改必要內容即可完成配

springboot 整合mybatis-plus mysql

【前言】注意mybatis-plus版本如果和springboot 版本有關係,我當時用的springboot-2.1.4.REL

springboot-整合mybatis-mysql-redis-quartzredis整合時就報錯

 .   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  )

SpringBoot 整合mybatis 及使用generatorpageHelper外掛

SpringBoot 整合mybatis 及使用generator,pageHelper外掛 一.新建springBoot專案 next next next finish 二.pom檔案配置 <?xml version="1.0" encoding="UTF-8

SpringBoot整合mybatisSpringBoot中的junit測試

1、pom檔案中引入mybatis依賴:mybatis-spring-boot-starter 和mysql驅動依賴:mysql-connector-java,以及spring-boot-starter-test依賴用於junit測試        

使用STS建立springboot整合mybatis+mysql+maven專案

這個專案我已經傳到CSDN資源上面了,大家如果需要,可以點選下載: 使用mybatis-generator逆向生成dao,entity,mapper檔案,在我之前的部落格中有專門的介紹, 部落格:《Mybatis-Generator反向自動生成Dao、Entity

Springboot整合mybatis連線資料庫

1.匯入相關jar包 使用maven匯入,pom.xml配置如下 <!--繼承父類--> <parent> <groupId>org.springframework.boot</groupId> <artifactId&g

SpringBoot2.X (二十五):SpringBoot整合 Mybatis + MySQL CURD 示例

話不多數,直接開始擼程式碼… 工程結構圖 開始之前先放張工程結構圖 1、maven 依賴: <!-- Web 依賴--> <dependency>

springboot整合mybatis-plus以及mybatis-plus入門使用

mybatis-plus是基於mybatis,相對於mybatis,他有許多特性是比較好用的,比如分頁查詢、表字段自動轉換為實體類屬性等,使用mybatis-plus與Spring Data JPA有點相似的地方,個人覺得mybatis-plus的分頁比JPA的分頁好用。其實

SpringBoot整合Mybatis-Plus和PageHelper分頁外掛附專案原始碼

1 pom.xml配置檔案 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3

springboot整合MyBatisUnsatisfied dependency expressed through field 'payParamMapper'

最近在做專案時候,使用springboot+mybatais時候,遇到下面這個問題,一時大意,記錄下異常資訊和解決方式 org.springframework.beans.factory.UnsatisfiedDependencyException: Erro

springboot 整合mybatismapper介面和對應的mapper對映檔案放在同一個包下的配置

一、springboot整合mybatis後,需要進行幾個步驟的配置: 1、mapper包下的mapper介面都需要新增@Mapper註解。 2、啟動類上面新增@MapperScan(basepackages={"com.web.mapper"})註解。 3、需要在po

Springboot整合Mybatis使用TypeHandler來轉換資料庫中的資料

TypeHandler轉換指定資料庫中資料為Enum列舉   在一些時候,我們的資料庫需要存放一些例如狀態資訊的資料,通常的我們使用int整型來儲存,例如(0:失敗,1:成功)等,用這樣的資料是可以的,但對於前端的程式設計是不友好的,所以我們可以使用TypeHandler來進行一個轉換,將其轉化成一個列舉型

SpringBoot整合mybatis、shiro、redis實現基於資料庫的細粒度動態許可權管理系統例項

1.前言 本文主要介紹使用SpringBoot與shiro實現基於資料庫的細粒度動態許可權管理系統例項。 使用技術:SpringBoot、mybatis、shiro、thymeleaf、pagehelper、Mapper外掛、druid、dataTables

springboot整合mybatis使用一套程式切換不同的資料庫

因專案要求,需在滿足要求的時候mysql與oracle是鉅款進行切換,找到如下兩種方式進行切換: 一、更改配置檔案的掃描資訊,使用springboot需在配置檔案中配置mybatis的資訊,將mybatis的檔案掃描目錄進行變更即可,我的專案的命名規則是mapper底下的是mysql的xml

springboot整合mybatis註解開發thymeleaf的簡單使用

1、前言 之前玩過使用xml配置檔案整合mybatis,這次為了整合thymeleaf模板,選用簡單的註解完成資料庫的查詢。整合工具無非是引入依賴,新增配置完成此相關功能。玩過之後,記錄一下學習的過程,以備後續使用。 2、依賴引入 使用springboot開發,建議裝上springboo

SpringBoot整合Mybatis自定義攔截器實現拼接sql和修改

一、應用場景 1.分頁,如com.github.pagehelper的分頁外掛實現; 2.攔截sql做日誌監控; 3.統一對某些sql進行統一條件拼接,類似於分頁。 二、MyBatis的攔截器簡介 然後我們要知道攔截器攔截什麼樣的物件,攔截物件的什麼行為,什麼時候攔截? &n

SpringBoot整合MyBatis(iBatis)基於註解和XML兩種方式

工具 IDEA Maven 專案建立 1. 通過IDEA建立SpringBoot專案 2. 結構目錄和JAVA版本選擇 3. 新增MySQL和MyBatis支援 4. 新增Lombok外掛,簡化GET、SET方法 5. WEB支援和啟動類 6. 專

SpringBoot筆記(三)--- SpringBoot整合Mybatis連線資料庫

在筆記二的基礎上 1.在pom檔案中新增如下依賴    <!-- mysql -->     <dependency>         <groupId>mysql</groupId>         <artifac