Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e323cce

Browse files
Java:新增 Redis 相关简单 Demo;提升 MultiDataSource 在 Redis 异常时的稳定性
1 parent b49a061 commit e323cce

File tree

14 files changed

+593
-15
lines changed

14 files changed

+593
-15
lines changed

‎APIJSON-Java-Server/APIJSONBoot-MultiDataSource/src/main/java/apijson/demo/DemoSQLExecutor.java‎

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -57,20 +57,28 @@ public class DemoSQLExecutor extends APIJSONSQLExecutor {
5757
public static final RedisTemplate<String, String> REDIS_TEMPLATE;
5858
static {
5959
REDIS_TEMPLATE = new RedisTemplate<>();
60-
REDIS_TEMPLATE.setConnectionFactory(new JedisConnectionFactory(new RedisStandaloneConfiguration("127.0.0.1", 6379)));
61-
REDIS_TEMPLATE.setKeySerializer(new StringRedisSerializer());
62-
REDIS_TEMPLATE.setHashValueSerializer(new GenericToStringSerializer<>(Serializable.class));
63-
REDIS_TEMPLATE.setValueSerializer(new GenericToStringSerializer<>(Serializable.class));
64-
// REDIS_TEMPLATE.setValueSerializer(new FastJsonRedisSerializer<List<JSONObject>>(List.class));
65-
REDIS_TEMPLATE.afterPropertiesSet();
60+
try {
61+
REDIS_TEMPLATE.setConnectionFactory(new JedisConnectionFactory(new RedisStandaloneConfiguration("127.0.0.1", 6379)));
62+
REDIS_TEMPLATE.setKeySerializer(new StringRedisSerializer());
63+
REDIS_TEMPLATE.setHashValueSerializer(new GenericToStringSerializer<>(Serializable.class));
64+
REDIS_TEMPLATE.setValueSerializer(new GenericToStringSerializer<>(Serializable.class));
65+
// REDIS_TEMPLATE.setValueSerializer(new FastJsonRedisSerializer<List<JSONObject>>(List.class));
66+
REDIS_TEMPLATE.afterPropertiesSet();
67+
} catch (Throwable e) {
68+
e.printStackTrace();
69+
}
6670
}
6771

6872
// 可重写以下方法,支持 Redis 等单机全局缓存或分布式缓存
6973
@Override
7074
public List<JSONObject> getCache(String sql, SQLConfig config) {
7175
List<JSONObject> list = super.getCache(sql, config);
7276
if (list == null) {
73-
list = JSON.parseArray(REDIS_TEMPLATE.opsForValue().get(sql), JSONObject.class);
77+
try {
78+
list = JSON.parseArray(REDIS_TEMPLATE.opsForValue().get(sql), JSONObject.class);
79+
} catch (Throwable e) {
80+
e.printStackTrace();
81+
}
7482
}
7583
return list;
7684
}
@@ -81,21 +89,29 @@ public synchronized void putCache(String sql, List<JSONObject> list, SQLConfig c
8189

8290
String table = config != null && config.isMain() ? config.getTable() : null;
8391
if (table != null && DemoSQLConfig.CONFIG_TABLE_LIST.contains(table) == false) {
84-
if (config.isExplain() || RequestMethod.isHeadMethod(config.getMethod(), true)) {
85-
REDIS_TEMPLATE.opsForValue().set(sql, JSON.toJSONString(list), 10 * 60, TimeUnit.SECONDS);
86-
} else {
87-
REDIS_TEMPLATE.opsForValue().set(sql, JSON.toJSONString(list), USER_.equals(table) || PRIVACY_.equals(table) ? 10 * 60 : 60, TimeUnit.SECONDS);
92+
try {
93+
if (config.isExplain() || RequestMethod.isHeadMethod(config.getMethod(), true)) {
94+
REDIS_TEMPLATE.opsForValue().set(sql, JSON.toJSONString(list), 10 * 60, TimeUnit.SECONDS);
95+
} else {
96+
REDIS_TEMPLATE.opsForValue().set(sql, JSON.toJSONString(list), USER_.equals(table) || PRIVACY_.equals(table) ? 10 * 60 : 60, TimeUnit.SECONDS);
97+
}
98+
} catch (Throwable e) {
99+
e.printStackTrace();
88100
}
89101
}
90102
}
91103

92104
@Override
93105
public synchronized void removeCache(String sql, SQLConfig config) {
94106
super.removeCache(sql, config);
95-
if (config.getMethod() == RequestMethod.DELETE) { // 避免缓存击穿
96-
REDIS_TEMPLATE.expire(sql, 60, TimeUnit.SECONDS);
97-
} else {
98-
REDIS_TEMPLATE.delete(sql);
107+
try {
108+
if (config.getMethod() == RequestMethod.DELETE) { // 避免缓存击穿
109+
REDIS_TEMPLATE.expire(sql, 60, TimeUnit.SECONDS);
110+
} else {
111+
REDIS_TEMPLATE.delete(sql);
112+
}
113+
} catch (Throwable e) {
114+
e.printStackTrace();
99115
}
100116
}
101117

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/target/

‎APIJSON-Java-Server/APIJSONDemo-Redis/.idea/.gitignore‎

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎APIJSON-Java-Server/APIJSONDemo-Redis/.idea/compiler.xml‎

Lines changed: 13 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎APIJSON-Java-Server/APIJSONDemo-Redis/.idea/encodings.xml‎

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎APIJSON-Java-Server/APIJSONDemo-Redis/.idea/jarRepositories.xml‎

Lines changed: 35 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎APIJSON-Java-Server/APIJSONDemo-Redis/.idea/misc.xml‎

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# APIJSONDemo
2+
3+
APIJSON + SpringBoot 初级使用的最简单 Demo
4+
5+
### 运行
6+
7+
右键 DemoApplication > Run As > Java Application
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
6+
<groupId>apijson.demo</groupId>
7+
<artifactId>apijson-demo-redis</artifactId>
8+
<version>5.4.0</version>
9+
10+
<name>APIJSONDemo-Redis</name>
11+
<description>Demo project for Testing APIJSON Server based on SpringBoot</description>
12+
13+
<properties>
14+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
15+
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
16+
<java.version>1.8</java.version>
17+
</properties>
18+
19+
<dependencies>
20+
<!-- JDK 11+ 需要,否则启动报错 NoClassDefFoundError: javax/activation/UnsupportedDataTypeException -->
21+
<dependency>
22+
<groupId>javax.activation</groupId>
23+
<artifactId>activation</artifactId>
24+
<version>1.1.1</version>
25+
</dependency>
26+
27+
<!-- 需要的 APIJSON 相关依赖 -->
28+
<dependency>
29+
<groupId>com.github.APIJSON</groupId>
30+
<artifactId>apijson-framework</artifactId>
31+
<version>5.4.0</version>
32+
</dependency>
33+
34+
<!-- 需要用的数据库 JDBC 驱动 -->
35+
<dependency>
36+
<groupId>mysql</groupId>
37+
<artifactId>mysql-connector-java</artifactId>
38+
<version>8.0.29</version>
39+
</dependency>
40+
<dependency>
41+
<groupId>org.postgresql</groupId>
42+
<artifactId>postgresql</artifactId>
43+
<version>42.3.4</version>
44+
</dependency>
45+
<!-- Oracle, SQLServer 等其它数据库的 JDBC 驱动,可以在这里加上 Maven 依赖或 libs 目录放 Jar 包并依赖 -->
46+
47+
<!-- 需要用的 SpringBoot 框架,1.4.0 以上 -->
48+
<dependency>
49+
<groupId>org.springframework.boot</groupId>
50+
<artifactId>spring-boot-starter-web</artifactId>
51+
<version>2.5.13</version>
52+
</dependency>
53+
54+
<dependency>
55+
<groupId>redis.clients</groupId>
56+
<artifactId>jedis</artifactId>
57+
<version>3.9.0</version>
58+
</dependency>
59+
60+
<dependency>
61+
<groupId>org.springframework.data</groupId>
62+
<artifactId>spring-data-redis</artifactId>
63+
<version>2.4.0</version>
64+
<exclusions>
65+
<exclusion>
66+
<groupId>redis.clients</groupId>
67+
<artifactId>jedis</artifactId>
68+
</exclusion>
69+
</exclusions>
70+
</dependency>
71+
72+
</dependencies>
73+
74+
<build>
75+
<plugins>
76+
<plugin>
77+
<groupId>org.springframework.boot</groupId>
78+
<artifactId>spring-boot-maven-plugin</artifactId>
79+
<configuration>
80+
<fork>true</fork>
81+
<mainClass>apijson.demo.DemoApplication</mainClass>
82+
</configuration>
83+
<executions>
84+
<execution>
85+
<goals>
86+
<goal>repackage</goal>
87+
</goals>
88+
</execution>
89+
</executions>
90+
</plugin>
91+
<plugin>
92+
<groupId>org.apache.maven.plugins</groupId>
93+
<artifactId>maven-compiler-plugin</artifactId>
94+
<configuration>
95+
<source>1.8</source>
96+
<target>1.8</target>
97+
</configuration>
98+
</plugin>
99+
</plugins>
100+
</build>
101+
102+
<repositories>
103+
<!-- APIJSON 必须用到的托管平台 -->
104+
<repository>
105+
<id>jitpack.io</id>
106+
<url>https://jitpack.io</url>
107+
<snapshots>
108+
<enabled>true</enabled>
109+
</snapshots>
110+
</repository>
111+
112+
<repository>
113+
<id>spring-snapshots</id>
114+
<url>https://repo.spring.io/snapshot</url>
115+
<snapshots>
116+
<enabled>true</enabled>
117+
</snapshots>
118+
</repository>
119+
<repository>
120+
<id>spring-milestones</id>
121+
<url>https://repo.spring.io/milestone</url>
122+
</repository>
123+
</repositories>
124+
125+
</project>
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON)
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.*/
14+
15+
package apijson.demo;
16+
17+
import apijson.orm.SQLExecutor;
18+
import org.springframework.boot.SpringApplication;
19+
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
20+
import org.springframework.boot.autoconfigure.SpringBootApplication;
21+
import org.springframework.boot.context.properties.EnableConfigurationProperties;
22+
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
23+
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
24+
import org.springframework.context.annotation.Bean;
25+
import org.springframework.context.annotation.Configuration;
26+
import org.springframework.web.servlet.config.annotation.CorsRegistry;
27+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
28+
29+
import apijson.Log;
30+
import apijson.framework.APIJSONApplication;
31+
import apijson.framework.APIJSONCreator;
32+
import apijson.orm.SQLConfig;
33+
34+
35+
/**
36+
* Demo SpringBoot Application 主应用程序启动类
37+
* 右键这个类 > Run As > Java Application
38+
* 具体见 SpringBoot 文档
39+
* https://www.springcloud.cc/spring-boot.html#using-boot-locating-the-main-class
40+
*
41+
* @author Lemon
42+
*/
43+
@Configuration
44+
@SpringBootApplication
45+
@EnableConfigurationProperties
46+
public class DemoApplication implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
47+
48+
public static void main(String[] args) throws Exception {
49+
SpringApplication.run(DemoApplication.class, args);
50+
51+
Log.DEBUG = true;
52+
APIJSONApplication.init(false); // 4.4.0 以上需要这句来保证以上 static 代码块中给 DEFAULT_APIJSON_CREATOR 赋值会生效
53+
}
54+
55+
// SpringBoot 2.x 自定义端口方式
56+
@Override
57+
public void customize(ConfigurableServletWebServerFactory server) {
58+
server.setPort(8080);
59+
}
60+
61+
// 支持 APIAuto 中 JavaScript 代码跨域请求
62+
@Bean
63+
public WebMvcConfigurer corsConfigurer() {
64+
return new WebMvcConfigurer() {
65+
@Override
66+
public void addCorsMappings(CorsRegistry registry) {
67+
registry.addMapping("/**")
68+
.allowedOriginPatterns("*")
69+
.allowedMethods("*")
70+
.allowCredentials(true)
71+
.maxAge(3600);
72+
}
73+
};
74+
}
75+
76+
static {
77+
// 使用本项目的自定义处理类
78+
APIJSONApplication.DEFAULT_APIJSON_CREATOR = new APIJSONCreator<Long>() {
79+
@Override
80+
public SQLConfig createSQLConfig() {
81+
return new DemoSQLConfig();
82+
}
83+
84+
@Override
85+
public SQLExecutor createSQLExecutor() {
86+
return new DemoSQLExecutor();
87+
}
88+
};
89+
90+
}
91+
92+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /