Skip to content

Commit b79680a

Browse files
committed
第七篇 : SpringBoot 整合 spring cache
1 parent 3f35698 commit b79680a

16 files changed

Lines changed: 644 additions & 0 deletions

springboot-cache/.gitignore

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/target/
2+
!.mvn/wrapper/maven-wrapper.jar
3+
4+
### STS ###
5+
.apt_generated
6+
.classpath
7+
.factorypath
8+
.project
9+
.settings
10+
.springBeans
11+
.sts4-cache
12+
13+
### IntelliJ IDEA ###
14+
.idea
15+
*.iws
16+
*.iml
17+
*.ipr
18+
19+
### NetBeans ###
20+
/nbproject/private/
21+
/build/
22+
/nbbuild/
23+
/dist/
24+
/nbdist/
25+
/.nb-gradle/
47.2 KB
Binary file not shown.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip

springboot-cache/pom.xml

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
6+
<groupId>com.gf</groupId>
7+
<artifactId>springboot-cache</artifactId>
8+
<version>0.0.1-SNAPSHOT</version>
9+
<packaging>jar</packaging>
10+
11+
<name>springboot-cache</name>
12+
<description>Demo project for Spring Boot</description>
13+
14+
<parent>
15+
<groupId>org.springframework.boot</groupId>
16+
<artifactId>spring-boot-starter-parent</artifactId>
17+
<version>2.0.5.RELEASE</version>
18+
<relativePath/> <!-- lookup parent from repository -->
19+
</parent>
20+
21+
<properties>
22+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23+
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
24+
<java.version>1.8</java.version>
25+
</properties>
26+
27+
<dependencies>
28+
<dependency>
29+
<groupId>org.springframework.boot</groupId>
30+
<artifactId>spring-boot-starter-cache</artifactId>
31+
</dependency>
32+
<dependency>
33+
<groupId>org.springframework.boot</groupId>
34+
<artifactId>spring-boot-starter-data-redis</artifactId>
35+
</dependency>
36+
<dependency>
37+
<groupId>org.springframework.boot</groupId>
38+
<artifactId>spring-boot-starter-web</artifactId>
39+
</dependency>
40+
41+
<dependency>
42+
<groupId>com.alibaba</groupId>
43+
<artifactId>fastjson</artifactId>
44+
<version>1.2.51</version>
45+
</dependency>
46+
47+
<dependency>
48+
<groupId>mysql</groupId>
49+
<artifactId>mysql-connector-java</artifactId>
50+
<scope>runtime</scope>
51+
</dependency>
52+
53+
<dependency>
54+
<groupId>org.projectlombok</groupId>
55+
<artifactId>lombok</artifactId>
56+
<version>1.18.2</version>
57+
<scope>provided</scope>
58+
</dependency>
59+
60+
<dependency>
61+
<groupId>com.baomidou</groupId>
62+
<artifactId>mybatis-plus-boot-starter</artifactId>
63+
<version>3.0.1</version>
64+
</dependency>
65+
66+
<dependency>
67+
<groupId>org.apache.velocity</groupId>
68+
<artifactId>velocity</artifactId>
69+
<version>1.7</version>
70+
</dependency>
71+
72+
<dependency>
73+
<groupId>org.springframework.boot</groupId>
74+
<artifactId>spring-boot-starter-test</artifactId>
75+
<scope>test</scope>
76+
</dependency>
77+
</dependencies>
78+
79+
<build>
80+
<plugins>
81+
<plugin>
82+
<groupId>org.springframework.boot</groupId>
83+
<artifactId>spring-boot-maven-plugin</artifactId>
84+
</plugin>
85+
</plugins>
86+
</build>
87+
88+
89+
</project>
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.gf;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
import org.springframework.cache.annotation.EnableCaching;
6+
7+
@EnableCaching
8+
@SpringBootApplication
9+
public class SpringbootCacheApplication {
10+
11+
public static void main(String[] args) {
12+
SpringApplication.run( SpringbootCacheApplication.class, args);
13+
}
14+
}
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
package com.gf.config;
2+
3+
4+
import com.baomidou.mybatisplus.annotation.DbType;
5+
import com.baomidou.mybatisplus.core.toolkit.StringPool;
6+
import com.baomidou.mybatisplus.generator.AutoGenerator;
7+
import com.baomidou.mybatisplus.generator.InjectionConfig;
8+
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
9+
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
10+
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
11+
import com.baomidou.mybatisplus.generator.config.PackageConfig;
12+
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
13+
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
14+
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
15+
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
16+
17+
import java.util.ArrayList;
18+
import java.util.List;
19+
20+
21+
public class CodeGenerator {
22+
23+
public static void main(String[] args) throws InterruptedException {
24+
AutoGenerator mpg = new AutoGenerator();
25+
26+
// 全局配置
27+
GlobalConfig gc = new GlobalConfig();
28+
String projectPath = System.getProperty("user.dir");
29+
gc.setOutputDir(projectPath + "/src/main/java");
30+
gc.setFileOverride(true);
31+
gc.setActiveRecord(true);
32+
gc.setEnableCache(false);// XML 二级缓存
33+
gc.setBaseResultMap(true);// XML ResultMap
34+
gc.setBaseColumnList(true);// XML columList
35+
gc.setOpen(false);
36+
gc.setAuthor("gf");
37+
38+
39+
// 自定义文件命名,注意 %s 会自动填充表实体属性!
40+
gc.setMapperName("%sMapper");
41+
gc.setXmlName("%sMapper");
42+
gc.setServiceName("%sService");
43+
gc.setServiceImplName("%sServiceImpl");
44+
gc.setControllerName("%sController");
45+
46+
mpg.setGlobalConfig(gc);
47+
48+
// 数据源配置
49+
DataSourceConfig dsc = new DataSourceConfig();
50+
dsc.setDbType( DbType.MYSQL);
51+
dsc.setDriverName("com.mysql.jdbc.Driver");
52+
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?useSSL=false");
53+
dsc.setUsername("root");
54+
dsc.setPassword("xxxxxx");
55+
mpg.setDataSource(dsc);
56+
57+
// 包配置
58+
PackageConfig pc = new PackageConfig();
59+
pc.setParent("com.gf");
60+
pc.setController( "controller");
61+
pc.setEntity( "entity" );
62+
//pc.setModuleName("test");
63+
mpg.setPackageInfo(pc);
64+
65+
// 自定义配置
66+
InjectionConfig cfg = new InjectionConfig() {
67+
@Override
68+
public void initMap() {
69+
// to do nothing
70+
}
71+
};
72+
List<FileOutConfig> focList = new ArrayList<>();
73+
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
74+
@Override
75+
public String outputFile(TableInfo tableInfo) {
76+
// 自定义输入文件名称
77+
return projectPath + "/src/main/resources/mapper/"
78+
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
79+
}
80+
});
81+
cfg.setFileOutConfigList(focList);
82+
mpg.setCfg(cfg);
83+
mpg.setTemplate(new TemplateConfig().setXml(null));
84+
85+
// 策略配置
86+
StrategyConfig strategy = new StrategyConfig();
87+
//此处可以修改为您的表前缀
88+
strategy.setTablePrefix(new String[] { "tb_"});
89+
// 表名生成策略
90+
strategy.setNaming(NamingStrategy.underline_to_camel);
91+
// 需要生成的表
92+
strategy.setInclude(new String[] { "tb_employee" });
93+
// 排除生成的表
94+
//strategy.setExclude(new String[]{"test"});
95+
strategy.setEntityLombokModel( true );
96+
97+
mpg.setStrategy(strategy);
98+
99+
// 执行生成
100+
mpg.execute();
101+
}
102+
103+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.gf.config;
2+
3+
4+
import com.alibaba.fastjson.parser.ParserConfig;
5+
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
6+
import org.springframework.context.annotation.Bean;
7+
import org.springframework.context.annotation.Configuration;
8+
import org.springframework.data.redis.cache.RedisCacheConfiguration;
9+
import org.springframework.data.redis.cache.RedisCacheManager;
10+
import org.springframework.data.redis.connection.RedisConnectionFactory;
11+
import org.springframework.data.redis.core.RedisTemplate;
12+
import org.springframework.data.redis.serializer.RedisSerializationContext;
13+
import org.springframework.data.redis.serializer.StringRedisSerializer;
14+
15+
@Configuration
16+
public class RedisConfig {
17+
18+
@Bean
19+
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
20+
RedisTemplate<Object, Object> template = new RedisTemplate<>();
21+
template.setConnectionFactory(redisConnectionFactory);
22+
23+
GenericFastJsonRedisSerializer serializer = new GenericFastJsonRedisSerializer();
24+
25+
ParserConfig.getGlobalInstance().addAccept("com.gf.");
26+
27+
//key序列化方式
28+
template.setKeySerializer(new StringRedisSerializer());
29+
//value序列化
30+
template.setValueSerializer(serializer);
31+
//value hashmap序列化
32+
template.setHashValueSerializer(serializer);
33+
template.afterPropertiesSet();
34+
35+
return template;
36+
}
37+
38+
@Bean
39+
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
40+
41+
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
42+
43+
GenericFastJsonRedisSerializer serializer = new GenericFastJsonRedisSerializer();
44+
45+
ParserConfig.getGlobalInstance().addAccept("com.gf.");
46+
47+
config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
48+
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer))
49+
.disableCachingNullValues();
50+
51+
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config);
52+
53+
54+
return builder.build();
55+
}
56+
57+
58+
}
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package com.gf.controller;
2+
3+
4+
import com.gf.entity.Employee;
5+
import com.gf.service.EmployeeService;
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
import org.springframework.data.redis.core.RedisTemplate;
8+
import org.springframework.web.bind.annotation.DeleteMapping;
9+
import org.springframework.web.bind.annotation.GetMapping;
10+
import org.springframework.web.bind.annotation.PathVariable;
11+
import org.springframework.web.bind.annotation.PostMapping;
12+
import org.springframework.web.bind.annotation.RequestMapping;
13+
14+
import org.springframework.web.bind.annotation.RequestMethod;
15+
import org.springframework.web.bind.annotation.RequestParam;
16+
import org.springframework.web.bind.annotation.RestController;
17+
18+
import java.util.List;
19+
20+
/**
21+
* <p>
22+
* 前端控制器
23+
* </p>
24+
*
25+
* @author gf
26+
* @since 2018-11-25
27+
*/
28+
@RestController
29+
@RequestMapping("/employee")
30+
public class EmployeeController {
31+
32+
33+
@Autowired
34+
EmployeeService employeeService;
35+
36+
@Autowired
37+
private RedisTemplate redisTemplate;
38+
39+
@GetMapping(value = "/list")
40+
public List<Employee> getEmployees() {
41+
return employeeService.list( null );
42+
}
43+
44+
@GetMapping(value = "/{id}")
45+
public Employee getEmployeeById(@PathVariable("id") int id) {
46+
return employeeService.getById( id );
47+
}
48+
49+
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
50+
public String updateEmployee(@PathVariable("id") int id, @RequestParam(value = "lastName", required = true) String lastName,
51+
@RequestParam(value = "email", required = true) String email , @RequestParam(value = "gender", required = true) int gender , @RequestParam(value = "dId", required = true) int dId) {
52+
Employee employee = new Employee();
53+
employee.setId( id );
54+
employee.setLastName( lastName );
55+
employee.setEmail( email );
56+
employee.setGender( gender );
57+
employee.setDId( dId );
58+
59+
Employee res = employeeService.updateEmployeeById( employee );
60+
61+
if (res != null) {
62+
return "update success";
63+
} else {
64+
return "update fail";
65+
}
66+
67+
}
68+
69+
@DeleteMapping(value = "/{id}")
70+
public String delete(@PathVariable(value = "id")int id) {
71+
boolean b = employeeService.removeById( id );
72+
73+
if(b) {
74+
return "delete success";
75+
}else {
76+
return "delete fail";
77+
}
78+
79+
}
80+
81+
@PostMapping(value = "")
82+
public String postEmployee(@RequestParam(value = "lastName", required = true) String lastName,
83+
@RequestParam(value = "email", required = true) String email , @RequestParam(value = "gender", required = true) int gender , @RequestParam(value = "dId", required = true) int dId) {
84+
85+
Employee employee = new Employee();
86+
employee.setLastName( lastName );
87+
employee.setEmail( email );
88+
employee.setGender( gender );
89+
employee.setDId( dId );
90+
boolean b = employeeService.save( employee );
91+
92+
if(b) {
93+
return "sava success";
94+
}else {
95+
return "sava fail";
96+
}
97+
98+
}
99+
100+
101+
}

0 commit comments

Comments
 (0)