本例场景:
调用Controller服务,第一次查库,并保存到redis缓存,第二次时直接从缓存中读取
1.本例环境
springboot + redis + mybatis + IntelliJ IDEA
本例源码下载地址: https://github.com/zhangbeizhen/springboot-redis
2.创建Spring Initializr项目
3.application.yml配置
1>.配置数据源,配置mybaits,配置redis等
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/zbzdb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#返回json时间格式
jackson:
date-format: yyyy-MM-dd HH:mm:ss
joda-date-time-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
#redis配置
redis:
host: 172.16.4.156
#驼峰命名
mybatis:
configuration:
map-underscore-to-camel-case: true
#服务器端口
server:
port: 8090
#日志打印
logging:
level:
com.zbz.mapper: debug
debug:
true
4.在SpringbootRedisApplication类引入redis缓存扫描注解
@MapperScan("com.zbz.mapper")
@EnableCaching
@SpringBootApplication
public class SpringbootRedisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootRedisApplication.class, args);
}
}
5.在MyRedisConfig自定义自动配置类
@Configuration
public class MyRedisConfig {
@Bean
public RedisTemplate<Object, Employee> empRedisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Employee> serializer = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
template.setDefaultSerializer(serializer);
return template;
}
@Bean
public RedisCacheManager empCacheManager(RedisTemplate<Object, Employee> empRedisTemplate){
RedisCacheManager cacheManager = new RedisCacheManager(empRedisTemplate);
//使用前缀,默认会将CacheName作为key的前缀
cacheManager.setUsePrefix(true);
return cacheManager;
}
}
6.在DruidConfig配置数据源自动配置类
@Configuration
public class DruidConfig {
/**注入配置文件信息- application.yml */
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
}
7.EmployeeService服务类使用redis缓存
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
/**注入redis缓存管理器*/
@Qualifier("empCacheManager")
@Autowired
RedisCacheManager deptCacheManager;
/**查*/
@Cacheable(cacheNames = "emp",cacheManager = "empCacheManager")
public Employee getEmployee(Integer id) {
System.out.println("从数据库获取数据开始......");
Employee employee = employeeMapper.getEmployeeById(id);
System.out.println("从数据库获取数据结束......");
return employee;
}
}
8.EmployeeMapper类
@Mapper
public interface EmployeeMapper {
@Select("SELECT * FROM employee WHERE id=#{id}")
public Employee getEmployeeById(Integer id);
}
9.EmployeeController类
@RestController
@RequestMapping("/emp")
public class EmployeeController {
@Autowired
EmployeeService employeeService;
/**
* 查
*/
@GetMapping("/query/{id}")
public Employee getEmployee(@PathVariable("id") Integer id) {
Employee employee = employeeService.getEmployee(id);
return employee;
}
}
10.Employee实体类
public class Employee implements Serializable {
private Integer id;
private String lastName;
private String email;
private Integer gender;
private String cardNumber;
/** 岗位 */
private String post;
/** 数据库字段: department_id 开启驼峰命名后可以自动匹配*/
private Integer departmentId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
}
11.建表语句
drop table if exists employee;
CREATE TABLE `employee` (
`id` INT(16) NOT NULL AUTO_INCREMENT COMMENT '编号',
`last_name` VARCHAR(128) DEFAULT NULL COMMENT '姓名',
`email` VARCHAR(128) DEFAULT NULL COMMENT '邮件',
`gender` INT(2) DEFAULT NULL COMMENT '性别',
`card_number` VARCHAR(64) DEFAULT NULL COMMENT '胸卡编号',
`post` VARCHAR(128) DEFAULT NULL COMMENT '岗位',
`department_id` INT(11) DEFAULT NULL COMMENT '部门编号',
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT='员工表' ;
12.测试
http://127.0.0.1:8090/emp/query/1
以上,TKS.