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.mzph.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 的整数倍,那么请将最后剩余的节点保持原有顺序。示例:给…