最近在看spring boot + mybatis+redis整合相关资料,自己亲手搭建了,现在分享一下过程,方便自己以后复习也希望给到看到的朋友一些借鉴。废话不多说开始了。
本文内容只是搭建一个简单框架,让各个模块能运行起来,实际业务会有更复杂处理需要大家自己去系统学习。
一:新建mave工程
引入pom依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<!--spring boot 基础依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<!--mybatis+mysql相关-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
<!--redis相关-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
</dependencies>
二、配置文件 application.yml
spring:
#mysql连接信息
datasource:
url: jdbc:mysql://localhost:3306/test2014
username: root
password: mysql2014
driver-class-name: com.mysql.jdbc.Driver
#redis连接信息
redis:
host: 127.0.0.1
port: 6379
jedis:
pool:
max-active: 8
# 打印sql
logging:
level:
zxl.boot.cache.mybatisTest.dao: debug
三、集成mybatis
1、实体类Friend
/**
* @author zhangxiaolong
* @ClassName Friend
* @Description
* @Date 2019/3/14 17:33
* @Version 1.0
**/
public class Friend {
private Long frId;
private String name;
private String nickname;
private Long age;
private String description;
public Friend(Long frId, String name, String nickname, Long age, String description) {
this.frId = frId;
this.name = name;
this.nickname = nickname;
this.age = age;
this.description = description;
}
public Friend() {
}
public Long getFrId() {
return frId;
}
public void setFrId(Long frId) {
this.frId = frId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
2、dao接口类;类上面添加@Mapper注解,数据操作方法上面加@Select(根据自己需要,@Update、@Insert、@Delete)。
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import zxl.boot.cache.mybatisTest.entity.Friend;
/**
* @author zhangxiaolong
* @ClassName FriendMapper
* @Description TODO
* @Date 2019/3/14 17:35
* @Version 1.0
**/
@Mapper
public interface FriendMapper {
@Select("select * from t_friend where fr_id = #{frId}")
Friend findFriend(@Param("frId") Long frId);
}
3、service业务类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import zxl.boot.cache.mybatisTest.dao.FriendMapper;
import zxl.boot.cache.mybatisTest.entity.Friend;
/**
* @author zhangxiaolong
* @ClassName FriendService
* @Description
* @Date 2019/3/14 17:37
* @Version 1.0
**/
@Service
public class FriendService {
@Autowired
private FriendMapper friendMapper;
@Cacheable(cacheNames = "friend", key = "#frId.toString()")
public Friend findFriend(Long frId){
return friendMapper.findFriend(frId);
}
}
@Service注册到spring容器;@Autowired 注入dao;@Cacheable为开启缓存。
4、controller类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import zxl.boot.cache.mybatisTest.entity.Friend;
import zxl.boot.cache.mybatisTest.service.FriendService;
/**
* @author zhangxiaolong
* @ClassName FriendController
* @Description TODO
* @Date 2019/3/14 17:46
* @Version 1.0
**/
@RestController
public class FriendController {
@Autowired
private FriendService friendService;
@GetMapping("/findFriend")
public Friend findFriend(@RequestParam Long frId){
return friendService.findFriend(frId);
}
}
@Restcontroller注解表明当前类为控制器。注入friendService;@GetMapping注解为方法设置访问路径(根据自己需要选择请求方式,@PostMapping、@PutMapping、@DeleteMapping);@RequestParam什么请求参数(并且可以设置是否必填,默认必填,此处没有展示;还有@ResponseBody注解);这里这是最简单的例子旨在让项目能正常运行起来,复杂业务实现大家自己去系统学习。
四、redis集成
1、pom已经集成见前文。
2、redis配置
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.util.Arrays;
/**
* @author zhangxiaolong
* @ClassName CacheConfig
* @Description TODO
* @Date 2019/3/15 9:47
* @Version 1.0
**/
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport{
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// 多个缓存的名称,目前只定义了一个
rcm.setCacheNames(Arrays.asList("friend"));
//设置缓存过期时间(秒)
rcm.setDefaultExpiration(600);
return rcm;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
此类读取redis配置,定义缓存名称(注意service中使用cacheNames要在这里定义),随spring容器启动时自动装载。@Configuration注解表明当前类为配置类;@EnableCaching注解开启内存;
五、启动类
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author zhangxiaolong
* @ClassName MybatisTestApplication
* @Description TODO
* @Date 2019/3/14 17:32
* @Version 1.0
**/
@SpringBootApplication
@MapperScan("zxl.boot.cache.mybatisTest.dao")
public class MybatisTestApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisTestApplication.class,args);
}
}
@SpringBootApplication注解表明当前类为spring boot启动类;@MapperScan注解指明dao所在包名,容器启动时会自动扫描。
六、运行项目
在启动类中运行main方法。
1、第一次打开链接 localhost:8080/findFriend?frId=2
成功返回数据,控制台打印查询语句,说明第一次缓存中没有数据从数据库查询。
2、第二次打开链接 localhost:8080/findFriend?frId=2
观察控制台没有打印查询语句,说明缓存生效。
七、源码地址
缓存注解说明推荐