mysql二級緩存redis_SpringBoot+Mybatis+redis(二級緩存)搭建

剛剛開始接觸Spring Boot,因為極簡單的配置開發,搭建一個通用的Spring Boot+Mybaitis+redis的開發框架。

一、用maven構建項目,pom.xml文件如下:

org.springframework.boot

spring-boot-starter-parent

1.5.1.RELEASE

org.springframework.boot

spring-boot-starter

org.springframework.boot

spring-boot-starter-logging

org.springframework.boot

spring-boot-starter-log4j2

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

org.mybatis.spring.boot

mybatis-spring-boot-starter

${mybatis-spring-boot}

mysql

mysql-connector-java

${mysql-connector}

org.springframework.boot

spring-boot-starter-cache

org.springframework.boot

spring-boot-starter-redis

1.4.6.RELEASE

junit

junit

4.12

因為用到了spring-boot-starter-parent的版本為1.5.1.RELEASE,所以需要指定spring-boot-starter-redis的版本為1.4.6.RELEASE。r

二、使用

配置文件application.properties如下

## 數據源配置

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8

spring.datasource.username=root

spring.datasource.password=123456

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

## Mybatis 配置

mybatis.typeAliasesPackage=org.spring.springboot.domain

mybatis.mapperLocations=classpath\:mapper/*.xml

mybatis.config-location=classpath\:mybatis-config.xml

logging.config=classpath\:log4j2.xml

spring.redis.host=localhost

spring.redis.port=6379

spring.redis.pool.max-idle=8

spring.redis.pool.min-idle=0

spring.redis.pool.max-active=8

spring.redis.pool.max-wait=-1

使用MyBatis

創建持久化bean

public class City implements Serializable{

/**

*

*/

private static final long serialVersionUID = -2081742442561524068L;

/**

* 城市編號

*/

private Long id;

/**

* 省份編號

*/

private Long provinceId;

/**

* 城市名稱

*/

private String cityName;

/**

* 描述

*/

private String description;

public Long getId() {

return id;

}

public void setId(Long id) {

this.id = id;

}

public Long getProvinceId() {

return provinceId;

}

public void setProvinceId(Long provinceId) {

this.provinceId = provinceId;

}

public String getCityName() {

return cityName;

}

public void setCityName(String cityName) {

this.cityName = cityName;

}

public String getDescription() {

return description;

}

public void setDescription(String description) {

this.description = description;

}

}

數據庫Dao接口,只有一個findByName方法

public interface CityDao {

/**

* 根據城市名稱,查詢城市信息

*

* @param cityName 城市名

*/

City findByName(@Param("cityName") String cityName);

}

CityMapper.xml

id, province_id, city_name, description

select

from city

where city_name = #{cityName}

三、因為使用了Redis作為二級緩存,所以在CityMapper.xml中添加了Redis的緩存實現

Mybatis與Redis的整合如下,在mybatis-config.xml開啟緩存

Redis的緩存實現

public class RedisCache implements Cache

{

private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);

@Autowired

private static JedisConnectionFactory jedisConnectionFactory;

private final String id;

/**

* The {@code ReadWriteLock}.

*/

private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

public RedisCache(final String id) {

if (id == null) {

throw new IllegalArgumentException("Cache instances require an ID");

}

logger.debug("MybatisRedisCache:id=" + id);

this.id = id;

}

@Override

public void clear()

{

JedisConnection connection = null;

try

{

connection = (JedisConnection) jedisConnectionFactory.getConnection();

connection.flushDb();

connection.flushAll();

}

catch (JedisConnectionException e)

{

e.printStackTrace();

}

finally

{

if (connection != null) {

connection.close();

}

}

}

@Override

public String getId()

{

return this.id;

}

@Override

public Object getObject(Object key)

{

Object result = null;

JedisConnection connection = null;

try

{

connection = (JedisConnection) jedisConnectionFactory.getConnection();

RedisSerializer serializer = new JdkSerializationRedisSerializer();

result = serializer.deserialize(connection.get(serializer.serialize(key)));

}

catch (JedisConnectionException 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;

JedisConnection connection = null;

try

{

connection = (JedisConnection) jedisConnectionFactory.getConnection();

result = Integer.valueOf(connection.dbSize().toString());

}

catch (JedisConnectionException e)

{

e.printStackTrace();

}

finally

{

if (connection != null) {

connection.close();

}

}

return result;

}

@Override

public void putObject(Object key, Object value)

{

JedisConnection connection = null;

try

{

connection = (JedisConnection) jedisConnectionFactory.getConnection();

RedisSerializer serializer = new JdkSerializationRedisSerializer();

connection.set(serializer.serialize(key), serializer.serialize(value));

}

catch (JedisConnectionException e)

{

e.printStackTrace();

}

finally

{

if (connection != null) {

connection.close();

}

}

}

@Override

public Object removeObject(Object key)

{

JedisConnection connection = null;

Object result = null;

try

{

connection = (JedisConnection) jedisConnectionFactory.getConnection();

RedisSerializer serializer = new JdkSerializationRedisSerializer();

result =connection.expire(serializer.serialize(key), 0);

}

catch (JedisConnectionException e)

{

e.printStackTrace();

}

finally

{

if (connection != null) {

connection.close();

}

}

return result;

}

public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {

RedisCache.jedisConnectionFactory = jedisConnectionFactory;

}

}

Redis的管理由Spring實現。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/529861.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/529861.shtml
英文地址,請注明出處:http://en.pswp.cn/news/529861.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

mysql自定義兩個條件排序_使用MySQL中的兩個不同列進行自定義排序?

為此,將ORDER BY子句與CASE語句一起使用。讓我們首先創建一個表-mysql> create table DemoTable1610-> (-> Marks int,-> Name varchar(20)-> ) ;使用插入命令在表中插入一些記錄-mysql> insert into DemoTable1610 values(85,John);mysql> in…

java獲取文件大小_Java中獲取文件大小的詳解及實例代碼

Java 獲取文件大小今天寫代碼時需要實現獲取文件大小的功能,目前有兩種實現方法,一種是使用File的length()方法;另外一種是使用FileInputStream的available()方法,當InputStream未進行read操作時,available()的大小應該…

java訪問權限friendly_Java的訪問權限

一.Java訪問權限飾詞(access specifiers)Java有public、protect、friendly、private四種訪問權限,并且這四訪問權限的訪問范圍越來越小。1. friendly1) 果一個class內的數據成員或方法沒有任何權限飾詞,那么它的缺省訪問權限就是f…

java 0 255_java – 什么(float)(par4 16255)/ 255.0F;意思?

帶alpha通道的RGB(通常稱為RGBA或aRGB)是四個字節打包成一個整數.AAAAAAAARRRRRRRRBBBBBBBBGGGGGGGG // the original par4, each char represents one bit.// where ARBG stands for alpha, red, blue and green bit.shift和運算符用于檢索每個字節.例如,par4>> 16&…

java ie下載文件名亂碼問題_php中強制下載文件的代碼(解決了IE下中文文件名亂碼問題)...

中間遇到一個問題是提交的中文文件名直接放到header里在IE下會變成亂碼,解決方法是將文件名先urlencode一下再放入header,如下。$file_name urlencode($_REQUEST[filename]);header("Pragma: public"); header("Expires: 0");heade…

java如何獲得當前路徑_在java中如何得到當前路徑

歸納一些網上取java路徑的方法:注明:如果從ANT啟動程序,this.getClass().getResource("")取出來的比較怪,直接用JAVA命令行調試就可成功。得到classpath和當前類的絕對路徑的一些方法獲得CLASSPATH之外路徑的方法&#…

java繼承總結_JAVA筆記:Java中的繼承總結

繼承:在Java中使用extends關鍵字來實現類的繼承 ,extends意思就是派生,所以子類也叫派生類,繼承的主要目的是擴展類的內容操作格式: class A{}; class B extends A{};子類B可以繼承父類A中的公用方法,也可…

java正則表達式 類_java正則表達式相關類的使用

import java.util.regex.Matcher;import java.util.regex.Pattern;public class TestZhengZe {public static void main(String[] args) {//匹配數字Pattern mac Pattern.compile("-?(0|([1-9][0-9]*))(\\.[0-9])?");System.out.println(mac.matcher("101.00…

Java轉置_Java實現單鏈表的逆轉置

單鏈表逆轉置的遞歸與非遞歸方式package link.reverse;// 定義一個單鏈表class Node {//變量private int record;//指向下一個對象private Node nextNode;public Node(int record) {this.record record;}public int getRecord() {return record;}public void setRecord(int re…

單利 java_Java設計模式-單利模式

單例模式作為對象的創建模式,單例模式確保其某一個類只有一個實例,而且自行實例化并向整個系統提供這個實例,這個類稱為單例類。單例模式有以下特點:1、單例類只能有一個實例2、單例類必須自己創建自己的唯一實例3、單例類必須給其…

esp8266接7735_基于8266的ESPEASY固件接入HASS的教程(可無腦接入各類傳感...

首先國際慣例,先放上成果:QQ圖片20170629160143.png (172.48 KB, 下載次數: 3)2017-6-29 16:03 上傳如上圖所示,樓主把顆粒物傳感器和二氧化碳傳感器加入到了HASS里,當然,論壇之前也有諸位大神提供過類似固件和方法來實現這一目標…

java定義private_java9開始——接口中可以定義private私有方法

在傳統的Java編程中,被廣為人知的一個知識點是:java Interface接口中不能定義private私有方法。只允許我們定義public訪問權限的方法、抽象方法或靜態方法。但是從Java 9 開始,Interface 接口中允許定義私有方法和私有靜態方法。下面我們就來…

java poi生成excel文件_java poi 導出Excel文件

1,導包 poi-3.9-XXX.JAR2, 創建一個實體對象public class Student implements Serializable {/****/private static final long serialVersionUID 1L;private int id;private String name;private int age;private Date borth;public Student(int id, String name…

java中捕獲異常的作用_在Java中捕獲通用異常?

您可以傳遞Class對象并以編程方式檢查。public static void checkForException(String message,Class exceptionType, ExpectedExceptionBlock block) {try {block.exceptionThrowingCode();} catch (Exception ex) {if ( exceptionType.isInstance(ex) ) {return;} else {thro…

java如何循環調用方法_Java:調用方法的“中斷”循環?

我的小程序有點問題。我有一個JOptionPane要求一個數字,如果該數字小于10,則一個循環會一直持續下去,并永遠做下去,繼續詢問數字。 在該循環內,我調用一個方法,將int作為參數。 在該方法中,我需…

隨機投點法計算定積分java_11 隨機模擬積分 | 統計計算

11.4 高維定積分上面的兩種計算一元函數定積分的方法可以很容易地推廣到多元函數定積分,或稱高維定積分。設\(d\)元函數\(h(x_1, x_2, \dots, x_d)\)定義于超矩形\[\begin{aligned}C \{(x_1, x_2, \ldots, x_d): a_i \leq x_i \leq b_i, i1,2,\ldots,d \}\end{alig…

java el ognl_EL和OGNL表達式的區分

OGNL是通常要結合Struts 2的標志一起使用,如 struts頁面中不能單獨使用,el可以單獨使用 ${sessionScope.username}頁面取值區別:名稱servletognl elparametersre…

java query包,有沒有Java的http_build_query函數的Java等價物?

I have a Map with my data and want to build a query string with it, just like I would with http_build_query on PHP. Im not sure if this code is the best implementation of it or if Im forgetting something?public String toQueryString(Map, ?> data) throw…

JAVA不同類型數組重載_java學習筆記--java中的方法與數組

方法完成特定功能的代碼塊方法的格式修飾符 返回值類型 方法名(參數類型 參數名1,參數類型 參數名2...){//方法體return 返回值;}方法的調用方式通過方法名調用方法根據形式參數列表將實際參數傳遞給方法定義方法的注意事項1.方法必須定義在類中2.方法與…

鏈表每k個反轉 java_K 個一組翻轉鏈表

leetcode第25題(困難)問題描述給你一個鏈表,每 k 個節點一組進行翻轉,請你返回翻轉后的鏈表。k 是一個正整數,它的值小于或等于鏈表的長度。如果節點總數不是 k 的整數倍,那么請將最后剩余的節點保持原有順序。示例:給…