springboot2.0 + mybatis 或者 springboot2.0 + redis 在网上可以找到很多资料,但是大都不全或者有这样那样的问题,所以便自己动手写了个demo,能只用 yaml 配置的,尽量不再写代码。
pom.xml
4.0.0
com.carlton
MybatisDemo
0.0.1-SNAPSHOT
jar
MybatisDemo
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.5.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-starter-cache
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
org.springframework.boot
spring-boot-devtools
runtime
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-configuration-processor
true
com.hynnet
json-lib
2.4
org.springframework.boot
spring-boot-maven-plugin
application.yml
---
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/trymaster?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123123
driver-class-name: com.mysql.jdbc.Driver
hikari: #springboot2.X 默认使用hikari作为数据源
minimum-idle: 5
maximum-pool-size: 15
connection-test-query: select 1
max-lifetime: 1800000
connection-timeout: 30000
pool-name: HikariDataPool
redis:
host: 127.0.0.1
port: 6379
password: 123123
database: 1
timeout: 60s
jedis:
pool:
max-idle: 50
min-idle: 5
max-wait: -1s
max-active: -1
transaction:
rollback-on-commit-failure: true
cache:
type: redis
cache-names: redisCache
redis:
time-to-live: 60s
use-key-prefix: true
key-prefix: cacheee
mybatis:
mapper-locations: com/carlton/demo/mapper/*.xml
type-aliases-package: com.carlton.demo.entity
logging:
level:
com.carlton.demo.mapper: debug
...
mybatis 因为直接用了springboot配置,不需要重写配置类。
redis 默认的 RedisTemplate 只支持存储 RedisTemplate
RedisConfig.java
package com.carlton.demo.conf;
import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.carlton.demo.util.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
/***
* Title: RedisConfig
* Description: reids配置类
* @author Carlton
* @date 2018年10月8日 下午4:37:44
*/
@Configuration
@ConfigurationProperties(prefix = "spring.cache.redis")
public class RedisConfig {
private Duration timeToLive = Duration.ZERO;
private String keyPrefix;
/***
* 注入封装RedisTemplate
*
* @author Carlton
* @date 2018年10月8日 下午4:27:06
* @param redisTemplate
* @return
*/
@Bean(name = "redisUtil")
public RedisUtil redisUtil(RedisTemplate redisTemplate) {
RedisUtil redisUtil = new RedisUtil();
redisUtil.setRedisTemplate(redisTemplate);
return redisUtil;
}
/***
* 实例化 RedisTemplate 对象
*
* @author Carlton
* @date 2018年10月8日 下午4:27:26
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisTemplate functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate<>();
initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
return redisTemplate;
}
/***
* 设置数据存入 redis 的序列化方式,并开启事务
*
* @author Carlton
* @date 2018年10月8日 下午4:27:18
* @param redisTemplate
* @param factory
*/
private void initDomainRedisTemplate(RedisTemplate redisTemplate, RedisConnectionFactory factory) {
// 如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to
// String!
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.setConnectionFactory(factory);
}
/***
* 自定义 RedisCacheManager 类,主要是设置序列化,解决乱码问题
*
* @author Carlton
* @date 2018年10月9日 下午2:46:15
* @param factory
* @return
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer
RedisUtil.java
redis工具类,封装各种常用方法,定义了一个变量 RedisTemplate
private RedisTemplate redisTemplate;
public void setRedisTemplate(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
具体代码不贴了,有兴趣请拉到文末看demo。
myBatis 实体类User 和mapper 省略,不过要注意的是,如果要使用 RedisCache,User 需要实现接口Serializable,否则报错。
测试类:
MybatisDemoApplicationTests.java
package com.carlton.demo;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import com.carlton.demo.entity.User;
import com.carlton.demo.mapper.UserMapper;
import com.carlton.demo.service.TestService;
import com.carlton.demo.util.RedisUtil;
@RunWith(SpringRunner.class)
@SpringBootTest
@EnableCaching
@ConfigurationProperties(prefix = "spring.cache.redis")
public class MybatisDemoApplicationTests {
private String keyPrefix;
@Autowired
DataSource dataSource;
@Autowired
RedisTemplate redisTemplate;
@Autowired
RedisUtil redisUtil;
@Autowired
UserMapper userMapper;
@Autowired
TestService testService;
@Test
public void test() {
System.out.println(dataSource.getClass());
}
@Test
public void set() {
// 测试 redisTemplate
redisTemplate.opsForValue().set("test:set", "testValue1多噢ffff噢噢噢发生的风");
String str = redisTemplate.opsForValue().get("test:set");
System.out.println(str);
// 测试 redisUtil 存取 String
redisUtil.set("eeeee", "1123地地道道的");
str = redisTemplate.opsForValue().get("eeeee");
System.out.println(str);
// 测试 reidsUtil 存储对象
User user = new User();
user.setAge(555);
user.setName("娃哈哈哈哈哈");
user.setId(55);
redisUtil.set("user:login", user);
}
@Test
public void cacheeMybatis() {
System.out.println("=============================测试cache 从数据库取=============================");
int id = 9;
User user = userMapper.selectByPrimaryKey(id);
System.out.println("-------------" + user.getId() + "-------------");
Object obj = redisUtil.get(keyPrefix + id);
System.out.println(obj.toString());
User user2 = (User) obj;
System.out.println(user2.getName());
}
@Test
public void cachee() {
System.out.println("=============================测试cache2 自定义生成=============================");
testService.testPrint();
User user = testService.gener(99, "qqq", 55);
System.out.println("-------------" + user.getId() + "-------------");
}
public void setKeyPrefix(String keyPrefix) {
this.keyPrefix = keyPrefix;
}
}
项目demo:
https://gitee.com/carltonq/springBoot2.X_MyBatis_Redis_demo.git