SpringBoot+Mybatis+Redis 实现缓存
搭建环境:
IDEA,jdk1.8,springboot1.5.3
新建springboot项目 依赖选择如下
springboot的推荐项目结构如下
其中
- root package结构:com.example.myproject
- 应用主类Application.java置于root package下,通常我们会在应用主类中做一些框架配置扫描等配置, 我们放在root package下可以帮助程序减少手工配置来加载到我们希望被Spring加载的内容
- 实体(Entity)与数据访问层(Repository)置于com.example.myproject.domain包下
- 逻辑层(Service)置于com.example.myproject.service包下
- Web层(web)置于com.example.myproject.web包下
搭建完的项目结构如下
本文采用mybatis-generator自动生成mapper,dao,entity,具体操作步骤见
https://blog.****.net/sinat_29774479/article/details/78542626 Intellji IDE使用mybatis-generator自动生成mybatis相关文件
删除application.properties 新建application.yml,
server:
port: 8080
spring:
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/world
username: root
password: 1234
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
redis:
host: 171.188.96.88
port: 6379
password: root
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.redis.domain
#pagehelper分页插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
添加redis的配置类,继承CachingConfigurerSupport根据自己需要重写方法
package com.redis.config;
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.cache.interceptor.KeyGenerator;
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.lang.reflect.Method;
/**
* Redis缓存配置类
*
* @author wl
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/*定义缓存数据 key 生成策略的bean
包名+类名+方法名+所有参数
*/
@Bean
public KeyGenerator wiselyKeyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/*要启用spring缓存支持,需创建一个 CacheManager的 bean,CacheManager 接口有很多实现,这里Redis 的集成,用 RedisCacheManager这个实现类
Redis 不是应用的共享内存,它只是一个内存服务器,就像 MySql 似的,
我们需要将应用连接到它并使用某种“语言”进行交互,因此我们还需要一个连接工厂以及一个 Spring 和 Redis 对话要用的 RedisTemplate,
这些都是 Redis 缓存所必需的配置,把它们都放在自定义的 CachingConfigurerSupport 中
*/
@Bean
public CacheManager cacheManager(
@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
// cacheManager.setDefaultExpiration(60);//设置缓存保留时间(seconds)
return cacheManager;
}
//1.项目启动时此方法先被注册成bean被spring管理
@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;
}
}
新建controller
package com.redis.controller;
import com.redis.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@RequestMapping("/query")
public class CityController {
@Autowired
private CityService cityService;
@ResponseBody
@RequestMapping("/findAll")
public Object findAll() {
return cityService.selectAllCity();
}
}
在CityMapper.xml中加入
<select id="selectAllCity" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from city
</select>
新建service
package com.redis.service;
import com.redis.domain.City;
import java.util.List;
public interface CityService {
List<City> selectAllCity();
}
实现service接口
package com.redis.service;
import com.redis.dao.CityMapper;
import com.redis.domain.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
@Service(value = "cityService")
public class CityServiceImpl implements CityService {
@Autowired
private CityMapper cityMapper;
@Override
@Cacheable(value = "all", keyGenerator = "wiselyKeyGenerator")
public List<City> selectAllCity() {
return cityMapper.selectAllCity();
}
}
查看redis数据库,发现第二次查询时间大幅减少,且出现配置中的缓存