1. 第一步创建项目pom文件如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.bhg</groupId>
<artifactId>springboot-cache02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-cache02</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--redis缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.0.8.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.创建数据库表,建表语句给上
/*
Navicat Premium Data Transfer
Source Server : 本地数据库
Source Server Type : MySQL
Source Server Version : 50022
Source Host : localhost:3306
Source Schema : mybatis
Target Server Type : MySQL
Target Server Version : 50022
File Encoding : 65001
Date: 07/08/2019 14:48:27
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`departmentName` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY USING BTREE (`id`)
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of department
-- ----------------------------
INSERT INTO `department` VALUES (1, '统一方便面');
INSERT INTO `department` VALUES (2, '海之言');
INSERT INTO `department` VALUES (3, '汤达人');
-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
`lastName` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`gender` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`email` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`d_id` int(11) NULL DEFAULT NULL,
PRIMARY KEY USING BTREE (`id`)
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of employee
-- ----------------------------
INSERT INTO `employee` VALUES (00000000001, '张三', '1', 'ashjdkashb@qq.com', 1);
INSERT INTO `employee` VALUES (00000000002, '王昭君', '2', 'asdadsda@qqcom', 2);
INSERT INTO `employee` VALUES (00000000003, '赵武', '1', 'asd.142.com', 1);
SET FOREIGN_KEY_CHECKS = 1;
3.springbootapplication要加上缓存注解与mapper自动扫描
@MapperScan("com.bhg.springbootcache02.mapper")
@EnableCaching
@SpringBootApplication
public class SpringbootCache02Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootCache02Application.class, args);
}
}
4.mapper接口,由于是测试我就直接用注解谢了
package com.bhg.springbootcache02.mapper;
import com.bhg.springbootcache02.bean.Employee;
import org.apache.ibatis.annotations.*;
/**
*
* @author bard
*/
@Mapper
public interface EmployeeMapper {
/**
* 根据id查询员工信息
* @param id id
* @return 员工类信息
*/
@Select("select * from employee where id = #{id}")
Employee getEmpById(Integer id);
/**
* 更新员工表信息
* @param employee
*/
@Update("update employee set lastName=#{lastName},email=#{email},gender=#{gender}, d_id=#{dId} where id=#{id}")
void updateEmp(Employee employee);
/**
* 删除员工信息
* @param id id
*/
@Delete("delete from employee where id-#{id}")
void deleteEmpById(Integer id);
/**
* 插入员工信息
* @param employee 员工信息
*/
@Insert("insert into employee(lastName,email,gender,d_id) value (#{lastName},#{email},#{gender},#{d_id})")
void insertEmployee(Employee employee);
}
package com.bhg.springbootcache02.mapper;
import com.bhg.springbootcache02.bean.Department;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
/**
* @Date: 2019-8-7
* @author bard
*/
@Mapper
public interface DepartmentMapper {
/**
* 通过id查询部门信息
* @param id id
* @return department类信息
*/
@Select("SELECT * FROM DEPARTMENT WHERE ID =#{id}")
Department getDeptById(Integer id);
}
5.service层
package com.bhg.springbootcache02.service;
import com.bhg.springbootcache02.bean.Department;
/**
*
* @author bard
*/
public interface DepartmentService {
/**
* 通过id查询部门数据
* @param id id
* @return 部门数据
*/
Department getDeptById(Integer id);
}
package com.bhg.springbootcache02.service;
import com.bhg.springbootcache02.bean.Employee;
/**
* @Description
* @FileName: EmployeeService
* @Author: bard
* @Date: 2019/8/6 10:12
*/
public interface EmployeeService {
/**
* 根据id查询员工信息
*
* @param id id
* @return 员工类信息
*/
Employee getEmpById(Integer id);
/**
* 更新员工表信息
*
* @param employee
*/
void updateEmp(Employee employee);
/**
* 删除员工信息
*
* @param id id
*/
void deleteEmpById(Integer id);
/**
* 插入员工信息
*
* @param employee 员工信息
*/
void insertEmployee(Employee employee);
}
package com.bhg.springbootcache02.service.serviceimpl;
import com.bhg.springbootcache02.bean.Department;
import com.bhg.springbootcache02.mapper.DepartmentMapper;
import com.bhg.springbootcache02.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* @Description
* @FileName: EmployeeServiceImpl
* @Author: bard
* @Date: 2019/8/6 10:16
*/
@Service
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
DepartmentMapper departmentMapper;
@Override
@Cacheable(cacheNames = "dept", key = "#id",cacheManager = "cacheManager")
public Department getDeptById(Integer id) {
System.out.println("调用了方法");
return departmentMapper.getDeptById(id);
}
}
package com.bhg.springbootcache02.service.serviceimpl;
import com.bhg.springbootcache02.bean.Employee;
import com.bhg.springbootcache02.mapper.EmployeeMapper;
import com.bhg.springbootcache02.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* @Description
* @FileName: EmployeeServiceImpl
* @Author: bard
* @Date: 2019/8/6 10:16
*/
@CacheConfig(cacheManager = "cacheManager")
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
@Override
@Cacheable(cacheNames = "emp" ,key = "#id")
public Employee getEmpById(Integer id) {
System.out.println("调用了方法");
return employeeMapper.getEmpById(id);
}
@Override
public void updateEmp(Employee employee) {
employeeMapper.updateEmp(employee);
}
@Override
public void deleteEmpById(Integer id) {
employeeMapper.deleteEmpById(id);
}
@Override
public void insertEmployee(Employee employee) {
employeeMapper.insertEmployee(employee);
}
}
6controller层主要的方法选择了几个
package com.bhg.springbootcache02.controller;
import com.bhg.springbootcache02.bean.Department;
import com.bhg.springbootcache02.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Description
* @FileName: EmployeeController
* @Author: bard
* @Date: 2019/8/6 10:26
*/
@Controller
public class DepartmentController {
@RequestMapping("selectDeptById")
@ResponseBody
public String selectById(@RequestParam(defaultValue = "1") String id) {
Integer empId = Integer.valueOf(id);
Department dept = departmentService.getDeptById(empId);
String string = dept.toString();
return string;
}
@Autowired
DepartmentService departmentService;
}
package com.bhg.springbootcache02.controller;
import com.bhg.springbootcache02.bean.Employee;
import com.bhg.springbootcache02.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Description
* @FileName: EmployeeController
* @Author: bard
* @Date: 2019/8/6 10:26
*/
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;
@RequestMapping("selectById")
@ResponseBody
public String selectById(@RequestParam(defaultValue = "1") String id) {
Integer empId = Integer.valueOf(id);
Employee emp = employeeService.getEmpById(empId);
String string = emp.toString();
return string;
}
@Autowired
RedisTemplate<String, Employee> redisTemplate;
@ResponseBody
@RequestMapping("/test")
public String test(){
Employee employee=new Employee();
employee.setdId(1);
employee.setEmail("asykgdhjagsd@qq.com");
employee.setGender(1);
employee.setLastName("w2waw");
redisTemplate.opsForValue().set("hello", employee);
return employee.toString();
}
}
7.配置文件
7.1 application.properties文件
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
#开启驼峰命名
mybatis.configuration.map-underscore-to-camel-case=true
#redis配置-即redis主机地址
spring.redis.host=192.168.132.128
7.2 自己配置的文件,位置如图
package com.bhg.springbootcache02.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.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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.*;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @Description redis配置类信息,完成序列化操作的bean类注入
* @FileName: MyRedisConfig01
* @Author: bard
* @Date: 2019/8/7 14:12
*/
@Configuration
public class MyRedisConfig01 extends CachingConfigurerSupport {
private int defaultExpireTime=1800;
private int testExpireTime=180;
private String testCacheName="test";
@Bean
public RedisTemplate<?, ?> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<?, ?> template = new StringRedisTemplate(factory);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
RedisSerializer stringSerializer = new StringRedisSerializer();
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setKeySerializer(stringSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(stringSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory lettuceConnectionFactory) {
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(defaultExpireTime))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
.disableCachingNullValues();
Set<String> cacheNames = new HashSet<>();
cacheNames.add(testCacheName);
Map<String, RedisCacheConfiguration> configMap = new HashMap<>(2);
configMap.put(testCacheName, defaultCacheConfig.entryTtl(Duration.ofSeconds(testExpireTime)));
RedisCacheManager cacheManager = RedisCacheManager.builder(lettuceConnectionFactory)
.cacheDefaults(defaultCacheConfig)
.initialCacheNames(cacheNames)
.withInitialCacheConfigurations(configMap)
.build();
return cacheManager;
}
}
8. 总结对springboot的自动配置类理解还不够,对于注入相关的bean理解不够全面.导致配置的时候出了一写问题.使用springboot1.5.1和springboot2.1.6还是由些许区别的.