开发小手册

工具、配置

总结和为了防止自己迷路(已废弃,比如有些一些是过往收集的,还有部分工具类笔者在实习的时候使用Hutool已经集成)

其实是: 方便以后自己Copy.

Yml配置

SpringBoot目前阶段配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# 启动端口
server:
port: 9000

spring:
# 环境修改
profile:
active: dev
# 数据库相关
datasource:
url: jdbc:mysql://localhost:3306/testDataBases?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
username: root
password: 1qiulihang
driver-class-name: com.mysql.cj.jdbc.Driver
# 文件,请求
servlet:
multipart:
max-file-size: 2MB
max-request-size: 5MB
# druid数据源
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 初始化时建立物理连接的个数
initial-size: 5
# 连接池的最小空闲数量
min-idle: 5
# 连接池最大连接数量
max-active: 20
# 获取连接时最大等待时间,单位毫秒
max-wait: 60000
# 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
test-while-idle: true
# 既作为检测的间隔时间又作为testWhileIdel执行的依据
time-between-eviction-runs-millis: 60000
# 销毁线程时检测当前连接的最后活动时间和当前时间差大于该值时,关闭当前连接(配置连接在池中的最小生存时间)
min-evictable-idle-time-millis: 30000
# 用来检测数据库连接是否有效的sql 必须是一个查询语句(oracle中为 select 1 from dual)
validation-query: select 'x'
# 申请连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
test-on-borrow: false
# 归还连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
test-on-return: false
# 是否缓存preparedStatement, 也就是PSCache,PSCache对支持游标的数据库性能提升巨大,比如说oracle,在mysql下建议关闭。
pool-prepared-statements: false
# 置监控统计拦截的filters,去掉后监控界面sql无法统计,stat: 监控统计、Slf4j:日志记录、waLL: 防御sqL注入
filters: stat,wall,slf4j
# 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100
max-pool-prepared-statement-per-connection-size: -1
# 合并多个DruidDataSource的监控数据
use-global-data-source-stat: true
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connect-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
web-stat-filter:
# 是否启用StatFilter默认值true
enabled: true
# 添加过滤规则
url-pattern: /*
# 忽略过滤的格式
exclusions: /druid/*,*.js,*.gif,*.jpg,*.png,*.css,*.ico
stat-view-servlet:
# 是否启用StatViewServlet默认值true
enabled: true
# 访问路径为/druid时,跳转到StatViewServlet
url-pattern: /druid/*
# 是否能够重置数据
reset-enable: false
# 需要账号密码才能访问控制台,默认为root
login-username: root
login-password: root
# IP白名单
allow: 127.0.0.1 #上线后请将密码设置 复杂,且允许远程访问
# IP黑名单(共同存在时,deny优先于allow)
deny:
# swagger admin网页
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER
# 静态资源
web:
resources:
static-locations: [ classpath:/static/,classpath:/public,classpath:/resources ]
# jackon格式化配置
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
# session保存到redis
session:
store-type: redis
#Redis相关配置
redis:
host: localhost # docker 后修改
port: 6379
#password:123456
database: 0 #0是0号数据库,redis默认开启的16个数据库
timeout: 5000 #超时时间
jedis:
#Redis连接池配置
pool:
max-active: 8 #最大连接数
max-wait: 1ms #连接池最大阻塞等待时间
max-idle: 4 #连接池中最大空闲连接
min-idle: 0 #连接池中最小空闲连接
# 缓存
cache:
redis:
time-to-live: 1800000 #设置缓存有效期1800秒 1800 000毫秒
#邮箱基本配置
mail:
host: smtp.qq.com
#发送者邮箱
username: aaa@qq.com
#配置密码,注意不是真正的密码,而是刚刚申请到的授权码
password:
#默认的邮件编码为UTF-8
default-encoding: UTF-8
port: 465
#其他参数
properties:
mail:
#配置SSL 加密工厂
smtp:
ssl:
trust: smtp.qq.com
auth: true
starttls:
enable: true
required: true
socketFactory:
fallback: true
class: javax.net.ssl.SSLSocketFactory
port: 465
#开启debug模式,这样邮件发送过程的日志会在控制台打印出来,方便排查错误
debug: true
mybatis-plus:
configuration:
# Mybatis-Plus日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
# 逻辑删除
logic-delete-field: delFlag
logic-delete-value: 1
logic-not-delete-value: 0
id-type: auto
# 日志
logging:
# 日志级别
level:
root: info
org.springframework: error
org.apache: error
# 日志存放路径
file:
path: logs/

Swagger Bug配置

如果运行报错。Failed to start bean ‘documentationPluginsBootstrapper

是因为springboot2.6.x后会有兼容问题,Springboot2.6以后将SpringMVC 默认路径匹配策略从AntPathMatcher 更改为PathPatternParser,导致出错。

所以要么降springboot的版本,要么yml文件加上一个配置。

1
2
3
4
spring:
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER

swagger配置模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.web.*;
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
* Description: Swagger配置模板
*/
@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {
@Bean(value = "defaultApi2")
Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
//配置网站的基本信息
.apiInfo(new ApiInfoBuilder()
//网站标题
.title("接口文档")
//标题后面的版本号
.version("v1.0")
.description("mallchat接口文档")
//联系人信息
.contact(new Contact("阿斌", "<http://www.calyee.cn>", "599882460@qq.com"))
.build())
.select()
//指定接口的位置
.apis(RequestHandlerSelectors
.withClassAnnotation(RestController.class)
)
.paths(PathSelectors.any())
.build();
}
@Bean
public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
allEndpoints.addAll(webEndpoints);
allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
String basePath = webEndpointProperties.getBasePath();
EndpointMapping endpointMapping = new EndpointMapping(basePath);
boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
}
private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
}
}

启动 打开 http://localhost:8080/doc.html
即: 路径+端口/doc.html

Result结果集

Result

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* @ClassName result
* @Description 全局统一返回结果类
* @Author QiuLiHang
* @DATE 2023/7/7 007 15:49
* @Version 1.0
*/

@Data
public class Result<T> {

//返回码
private Integer code;

//返回消息
private String message;

//返回数据
private T data;

public Result(){}

// 返回数据
protected static <T> Result<T> build(T data) {
Result<T> result = new Result<T>();
if (data != null)
result.setData(data);
return result;
}

public static <T> Result<T> build(T body, Integer code, String message) {
Result<T> result = build(body);
result.setCode(code);
result.setMessage(message);
return result;
}

public static <T> Result<T> build(T body, ResultCodeEnum resultCodeEnum) {
Result<T> result = build(body);
result.setCode(resultCodeEnum.getCode());
result.setMessage(resultCodeEnum.getMessage());
return result;
}

public static<T> Result<T> ok(){
return Result.ok(null);
}

/**
* 操作成功
* @param data baseCategory1List
* @param <T>
* @return
*/
public static<T> Result<T> ok(T data){
Result<T> result = build(data);
return build(data, ResultCodeEnum.SUCCESS);
}

public static<T> Result<T> fail(){
return Result.fail(null);
}

/**
* 操作失败
* @param data
* @param <T>
* @return
*/
public static<T> Result<T> fail(T data){
Result<T> result = build(data);
return build(data, ResultCodeEnum.FAIL);
}

public Result<T> message(String msg){
this.setMessage(msg);
return this;
}

public Result<T> code(Integer code){
this.setCode(code);
return this;
}
}

ResultCodeEnum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 统一返回结果状态信息类
*/
@Getter
public enum ResultCodeEnum {

// 示例
SUCCESS(200,"成功"),
FAIL(201, "失败"),
SERVICE_ERROR(2012, "服务异常"),
DATA_ERROR(204, "数据异常"),
ILLEGAL_REQUEST(205, "非法请求"),
REPEAT_SUBMIT(206, "重复提交"),
ARGUMENT_VALID_ERROR(210, "参数校验异常"),

LOGIN_AUTH(208, "未登陆"),
PERMISSION(209, "没有权限"),
ACCOUNT_ERROR(214, "账号不正确"),
PASSWORD_ERROR(215, "密码不正确"),
LOGIN_MOBLE_ERROR( 216, "账号不正确"),
ACCOUNT_STOP( 217, "账号已停用"),
;

private Integer code;

private String message;

private ResultCodeEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
}

Redis工具及序列化方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
public class RedisUtils {

private static StringRedisTemplate stringRedisTemplate;

static {
RedisUtils.stringRedisTemplate = SpringUtil.getBean(StringRedisTemplate.class);
}

private static final String LUA_INCR_EXPIRE =
"local key,ttl=KEYS[1],ARGV[1] \n" +
" \n" +
"if redis.call('EXISTS',key)==0 then \n" +
" redis.call('SETEX',key,ttl,1) \n" +
" return 1 \n" +
"else \n" +
" return tonumber(redis.call('INCR',key)) \n" +
"end ";

public static Long inc(String key, int time, TimeUnit unit) {
RedisScript<Long> redisScript = new DefaultRedisScript<>(LUA_INCR_EXPIRE, Long.class);
return stringRedisTemplate.execute(redisScript, Collections.singletonList(key), String.valueOf(unit.toSeconds(time)));
}

/**
* 自增int
*
* @param key 键
* @param time 时间(秒)
*/
public static Integer integerInc(String key, int time, TimeUnit unit) {
RedisScript<Long> redisScript = new DefaultRedisScript<>(LUA_INCR_EXPIRE, Long.class);
Long result = stringRedisTemplate.execute(redisScript, Collections.singletonList(key), String.valueOf(unit.toSeconds(time)));
try {
return Integer.parseInt(result.toString());
} catch (Exception e) {
RedisUtils.del(key);
throw e;
}
}

/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
*/
public static Boolean expire(String key, long time) {
try {
if (time > 0) {
stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
return true;
}

/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @param timeUnit 单位
*/
public static Boolean expire(String key, long time, TimeUnit timeUnit) {
try {
if (time > 0) {
stringRedisTemplate.expire(key, time, timeUnit);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
return true;
}

/**
* 根据 key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public static Long getExpire(String key) {
return stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
}

/**
* 根据 key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public static Long getExpire(String key, TimeUnit timeUnit) {
return stringRedisTemplate.getExpire(key, timeUnit);
}

/**
* 查找匹配key
*
* @param pattern key
* @return /
*/
public static List<String> scan(String pattern) {
ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
RedisConnectionFactory factory = stringRedisTemplate.getConnectionFactory();
RedisConnection rc = Objects.requireNonNull(factory).getConnection();
Cursor<byte[]> cursor = rc.scan(options);
List<String> result = new ArrayList<>();
while (cursor.hasNext()) {
result.add(new String(cursor.next()));
}
try {
RedisConnectionUtils.releaseConnection(rc, factory);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return result;
}

/**
* 分页查询 key
*
* @param patternKey key
* @param page 页码
* @param size 每页数目
* @return /
*/
public static List<String> findKeysForPage(String patternKey, int page, int size) {
ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();
RedisConnectionFactory factory = stringRedisTemplate.getConnectionFactory();
RedisConnection rc = Objects.requireNonNull(factory).getConnection();
Cursor<byte[]> cursor = rc.scan(options);
List<String> result = new ArrayList<>(size);
int tmpIndex = 0;
int fromIndex = page * size;
int toIndex = page * size + size;
while (cursor.hasNext()) {
if (tmpIndex >= fromIndex && tmpIndex < toIndex) {
result.add(new String(cursor.next()));
tmpIndex++;
continue;
}
// 获取到满足条件的数据后,就可以退出了
if (tmpIndex >= toIndex) {
break;
}
tmpIndex++;
cursor.next();
}
try {
RedisConnectionUtils.releaseConnection(rc, factory);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return result;
}

/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public static Boolean hasKey(String key) {
try {
return stringRedisTemplate.hasKey(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}


/**
* 删除缓存
*
* @param keys
*/
public static void del(String... keys) {
if (keys != null && keys.length > 0) {
if (keys.length == 1) {
Boolean result = stringRedisTemplate.delete(keys[0]);
log.debug("--------------------------------------------");
log.debug("删除缓存:" + keys[0] + ",结果:" + result);
} else {
Set<String> keySet = new HashSet<>();
for (String key : keys) {
Set<String> stringSet = stringRedisTemplate.keys(key);
if (Objects.nonNull(stringSet) && !stringSet.isEmpty()) {
keySet.addAll(stringSet);
}
}
Long count = stringRedisTemplate.delete(keySet);
log.debug("--------------------------------------------");
log.debug("成功删除缓存:" + keySet);
log.debug("缓存删除数量:" + count + "个");
}
log.debug("--------------------------------------------");
}
}

public static void del(List<String> keys) {
stringRedisTemplate.delete(keys);
}

// ============================String=============================

/**
* 普通缓存获取
*
* @param key 键
* @return
*/
public static String get(String key) {
return key == null ? null : stringRedisTemplate.opsForValue().get(key);
}

/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public static Boolean set(String key, Object value) {
try {
stringRedisTemplate.opsForValue().set(key, objToStr(value));
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}

public static String getStr(String key) {
return get(key, String.class);
}

public static <T> T get(String key, Class<T> tClass) {
String s = get(key);
return toBeanOrNull(s, tClass);
}

public static <T> List<T> mget(Collection<String> keys, Class<T> tClass) {
List<String> list = stringRedisTemplate.opsForValue().multiGet(keys);
if (Objects.isNull(list)) {
return new ArrayList<>();
}
return list.stream().map(o -> toBeanOrNull(o, tClass)).collect(Collectors.toList());
}

static <T> T toBeanOrNull(String json, Class<T> tClass) {
return json == null ? null : JsonUtils.toObj(json, tClass);
}

public static String objToStr(Object o) {
return JsonUtils.toStr(o);
}

public static <T> void mset(Map<String, T> map, long time) {
Map<String, String> collect = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, (e) -> objToStr(e.getValue())));
stringRedisTemplate.opsForValue().multiSet(collect);
map.forEach((key, value) -> {
expire(key, time);
});
}


/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public static Boolean set(String key, Object value, long time) {
try {
if (time > 0) {
stringRedisTemplate.opsForValue().set(key, objToStr(value), time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}

/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间
* @param timeUnit 类型
* @return true成功 false 失败
*/
public static Boolean set(String key, Object value, long time, TimeUnit timeUnit) {
try {
if (time > 0) {
stringRedisTemplate.opsForValue().set(key, objToStr(value), time, timeUnit);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}

// ================================Map=================================

/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return
*/
public static Object hget(String key, String item) {
return stringRedisTemplate.opsForHash().get(key, item);
}

/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public static Map<Object, Object> hmget(String key) {
return stringRedisTemplate.opsForHash().entries(key);

}

/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public static Boolean hmset(String key, Map<String, Object> map) {
try {
stringRedisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}

/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public static Boolean hmset(String key, Map<String, Object> map, long time) {
try {
stringRedisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}

/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public static Boolean hset(String key, String item, Object value) {
try {
stringRedisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}

/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public static Boolean hset(String key, String item, Object value, long time) {
try {
stringRedisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}

/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public static void hdel(String key, Object... item) {
stringRedisTemplate.opsForHash().delete(key, item);
}

/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public static Boolean hHasKey(String key, String item) {
return stringRedisTemplate.opsForHash().hasKey(key, item);
}

/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public static Double hincr(String key, String item, double by) {
return stringRedisTemplate.opsForHash().increment(key, item, by);
}

/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public static Double hdecr(String key, String item, double by) {
return stringRedisTemplate.opsForHash().increment(key, item, -by);
}

// ============================set=============================

/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return
*/
public static Set<String> sGet(String key) {
try {
return stringRedisTemplate.opsForSet().members(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}

/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public static Boolean sHasKey(String key, Object value) {
try {
return stringRedisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}

/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public static Long sSet(String key, Object... values) {
try {
String[] s = new String[values.length];
for (int i = 0; i < values.length; i++) {
s[i] = objToStr(values[i]);
}
return stringRedisTemplate.opsForSet().add(key, s);
} catch (Exception e) {
log.error(e.getMessage(), e);
return 0L;
}
}

/**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public static Long sSetAndTime(String key, long time, Object... values) {
try {
String[] s = new String[values.length];
for (int i = 0; i < values.length; i++) {
s[i] = objToStr(values[i]);
}
Long count = stringRedisTemplate.opsForSet().add(key, s);
if (time > 0) {
expire(key, time);
}
return count;
} catch (Exception e) {
log.error(e.getMessage(), e);
return 0L;
}
}

/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public static Long sGetSetSize(String key) {
try {
return stringRedisTemplate.opsForSet().size(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
return 0L;
}
}

/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public static Long setRemove(String key, Object... values) {
try {
return stringRedisTemplate.opsForSet().remove(key, values);
} catch (Exception e) {
log.error(e.getMessage(), e);
return 0L;
}
}

// ===============================list=================================

/**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public static List<String> lGet(String key, long start, long end) {
try {
return stringRedisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}

/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public static Long lGetListSize(String key) {
try {
return stringRedisTemplate.opsForList().size(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
return 0L;
}
}

/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public static String lGetIndex(String key, long index) {
try {
return stringRedisTemplate.opsForList().index(key, index);
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}

/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public static Boolean lSet(String key, Object value) {
try {
stringRedisTemplate.opsForList().rightPush(key, objToStr(value));
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}

/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public static Boolean lSet(String key, Object value, long time) {
try {
stringRedisTemplate.opsForList().rightPush(key, objToStr(value));
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}

/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public static Boolean lSet(String key, List<Object> value) {
try {
List<String> list = new ArrayList<>();
for (Object item : value) {
list.add(objToStr(item));
}
stringRedisTemplate.opsForList().rightPushAll(key, list);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}

/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public static Boolean lSet(String key, List<Object> value, long time) {
try {
List<String> list = new ArrayList<>();
for (Object item : value) {
list.add(objToStr(item));
}
stringRedisTemplate.opsForList().rightPushAll(key, list);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}

/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return /
*/
public static Boolean lUpdateIndex(String key, long index, Object value) {
try {
stringRedisTemplate.opsForList().set(key, index, objToStr(value));
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}

/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public static Long lRemove(String key, long count, Object value) {
try {
return stringRedisTemplate.opsForList().remove(key, count, value);
} catch (Exception e) {
log.error(e.getMessage(), e);
return 0L;
}
}

/**
* @param prefix 前缀
* @param ids id
*/
public void delByKeys(String prefix, Set<Long> ids) {
Set<String> keys = new HashSet<>();
for (Long id : ids) {
Set<String> stringSet = stringRedisTemplate.keys(prefix + id);
if (Objects.nonNull(stringSet) && !stringSet.isEmpty()) {
keys.addAll(stringSet);
}
}
Long count = stringRedisTemplate.delete(keys);
// 此处提示可自行删除
log.debug("--------------------------------------------");
log.debug("成功删除缓存:" + keys.toString());
log.debug("缓存删除数量:" + count + "个");
log.debug("--------------------------------------------");
}
/**------------------zSet相关操作--------------------------------*/

/**
* 添加元素,有序集合是按照元素的score值由小到大排列
*
* @param key
* @param value
* @param score
* @return
*/
public static Boolean zAdd(String key, String value, double score) {
return stringRedisTemplate.opsForZSet().add(key, value, score);
}

public static Boolean zAdd(String key, Object value, double score) {
return zAdd(key, value.toString(), score);
}

public static Boolean zIsMember(String key, Object value) {
return Objects.nonNull(stringRedisTemplate.opsForZSet().score(key, value.toString()));
}

/**
* @param key
* @param values
* @return
*/
public Long zAdd(String key, Set<ZSetOperations.TypedTuple<String>> values) {
return stringRedisTemplate.opsForZSet().add(key, values);
}

/**
* @param key
* @param values
* @return
*/
public static Long zRemove(String key, Object... values) {
return stringRedisTemplate.opsForZSet().remove(key, values);
}

public static Long zRemove(String key, Object value) {
return zRemove(key, value.toString());
}

public static Long zRemove(String key, String value) {
return stringRedisTemplate.opsForZSet().remove(key, value);
}

/**
* 增加元素的score值,并返回增加后的值
*
* @param key
* @param value
* @param delta
* @return
*/
public static Double zIncrementScore(String key, String value, double delta) {
return stringRedisTemplate.opsForZSet().incrementScore(key, value, delta);
}

/**
* 返回元素在集合的排名,有序集合是按照元素的score值由小到大排列
*
* @param key
* @param value
* @return 0表示第一位
*/
public static Long zRank(String key, Object value) {
return stringRedisTemplate.opsForZSet().rank(key, value);
}

/**
* 返回元素在集合的排名,按元素的score值由大到小排列
*
* @param key
* @param value
* @return
*/
public static Long zReverseRank(String key, Object value) {
return stringRedisTemplate.opsForZSet().reverseRank(key, value);
}

/**
* 获取集合的元素, 从小到大排序
*
* @param key
* @param start 开始位置
* @param end 结束位置, -1查询所有
* @return
*/
public static Set<String> zRange(String key, long start, long end) {
return stringRedisTemplate.opsForZSet().range(key, start, end);
}

public static Set<String> zAll(String key) {
return stringRedisTemplate.opsForZSet().range(key, 0, -1);
}

/**
* 获取集合元素, 并且把score值也获取
*
* @param key
* @param start
* @param end
* @return
*/
public static Set<ZSetOperations.TypedTuple<String>> zRangeWithScores(String key, long start,
long end) {
return stringRedisTemplate.opsForZSet().rangeWithScores(key, start, end);
}

/**
* 根据Score值查询集合元素
*
* @param key
* @param min 最小值
* @param max 最大值
* @return
*/
public static Set<String> zRangeByScore(String key, double min, double max) {
return stringRedisTemplate.opsForZSet().rangeByScore(key, min, max);
}

/**
* 根据Score值查询集合元素, 从小到大排序
*
* @param key
* @param min 最小值
* @param max 最大值
* @return
*/
public static Set<ZSetOperations.TypedTuple<String>> zRangeByScoreWithScores(String key,
Double min, Double max) {
if (Objects.isNull(min)) {
min = Double.MIN_VALUE;
}
if (Objects.isNull(max)) {
max = Double.MAX_VALUE;
}
return stringRedisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max);
}

/**
* @param key
* @param min
* @param max
* @param start
* @param end
* @return
*/
public static Set<ZSetOperations.TypedTuple<String>> zRangeByScoreWithScores(String key,
double min, double max, long start, long end) {
return stringRedisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max,
start, end);
}

/**
* 获取集合的元素, 从大到小排序
*
* @param key
* @param start
* @param end
* @return
*/
public static Set<String> zReverseRange(String key, long start, long end) {
return stringRedisTemplate.opsForZSet().reverseRange(key, start, end);
}

// /**
// * 获取集合的元素, 从大到小排序, 并返回score值
// *
// * @param key
// * @param start
// * @param end
// * @return
// */
// public Set<TypedTuple<String>> zReverseRangeWithScores(String key,
// long start, long end) {
// return redisTemplate.opsForZSet().reverseRangeWithScores(key, start,
// end);
// }

/**
* 获取集合的元素, 从大到小排序, 并返回score值
*
* @param key
* @param pageSize
* @return
*/
public static Set<ZSetOperations.TypedTuple<String>> zReverseRangeWithScores(String key,
long pageSize) {
return stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, Double.MIN_VALUE,
Double.MAX_VALUE, 0, pageSize);
}

/**
* @param key
* @param max
* @param pageSize
* @return
*/
public static Set<ZSetOperations.TypedTuple<String>> zReverseRangeByScoreWithScores(String key,
double max, long pageSize) {
return stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, Double.MIN_VALUE, max,
1, pageSize);
}

// /**
// * 根据Score值查询集合元素, 从大到小排序
// *
// * @param key
// * @param min
// * @param max
// * @return
// */
// public Set<String> zReverseRangeByScore(String key, double min,
// double max) {
// return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max);
// }

// /**
// * 根据Score值查询集合元素, 从大到小排序
// *
// * @param key
// * @param min
// * @param max
// * @return
// */
// public Set<TypedTuple<String>> zReverseRangeByScoreWithScores(
// String key, double min, double max) {
// return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key,
// min, max);
// }


/**
* 根据score值获取集合元素数量
*
* @param key
* @param min
* @param max
* @return
*/
public static Long zCount(String key, double min, double max) {
return stringRedisTemplate.opsForZSet().count(key, min, max);
}

/**
* 获取集合大小
*
* @param key
* @return
*/
public static Long zSize(String key) {
return stringRedisTemplate.opsForZSet().size(key);
}

/**
* 获取集合大小
*
* @param key
* @return
*/
public static Long zCard(String key) {
return stringRedisTemplate.opsForZSet().zCard(key);
}

/**
* 获取集合中value元素的score值
*
* @param key
* @param value
* @return
*/
public static Double zScore(String key, Object value) {
return stringRedisTemplate.opsForZSet().score(key, value);
}

/**
* 移除指定索引位置的成员
*
* @param key
* @param start
* @param end
* @return
*/
public static Long zRemoveRange(String key, long start, long end) {
return stringRedisTemplate.opsForZSet().removeRange(key, start, end);
}

/**
* 根据指定的score值的范围来移除成员
*
* @param key
* @param min
* @param max
* @return
*/
public static Long zRemoveRangeByScore(String key, double min, double max) {
return stringRedisTemplate.opsForZSet().removeRangeByScore(key, min, max);
}

/**
* 获取key和otherKey的并集并存储在destKey中
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
public static Long zUnionAndStore(String key, String otherKey, String destKey) {
return stringRedisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey);
}

/**
* @param key
* @param otherKeys
* @param destKey
* @return
*/
public static Long zUnionAndStore(String key, Collection<String> otherKeys,
String destKey) {
return stringRedisTemplate.opsForZSet()
.unionAndStore(key, otherKeys, destKey);
}

/**
* 交集
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
public static Long zIntersectAndStore(String key, String otherKey,
String destKey) {
return stringRedisTemplate.opsForZSet().intersectAndStore(key, otherKey,
destKey);
}

/**
* 交集
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
public static Long zIntersectAndStore(String key, Collection<String> otherKeys,
String destKey) {
return stringRedisTemplate.opsForZSet().intersectAndStore(key, otherKeys,
destKey);
}
}

上面还需要附加一个JsonUtils

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

public class JsonUtils {
private static final ObjectMapper jsonMapper = new ObjectMapper();

public static <T> T toObj(String str, Class<T> clz) {
try {
return jsonMapper.readValue(str, clz);
} catch (JsonProcessingException e) {
throw new UnsupportedOperationException(e);
}
}

public static <T> T toObj(String str, TypeReference<T> clz) {
try {
return jsonMapper.readValue(str, clz);
} catch (JsonProcessingException e) {
throw new UnsupportedOperationException(e);
}
}

public static <T> List<T> toList(String str, Class<T> clz) {
try {
return jsonMapper.readValue(str, new TypeReference<List<T>>() {
});
} catch (JsonProcessingException e) {
throw new UnsupportedOperationException(e);
}
}

public static JsonNode toJsonNode(String str) {
try {
return jsonMapper.readTree(str);
} catch (JsonProcessingException e) {
throw new UnsupportedOperationException(e);
}
}

public static <T> T nodeToValue(JsonNode node, Class<T> clz) {
try {
return jsonMapper.treeToValue(node, clz);
} catch (JsonProcessingException e) {
throw new UnsupportedOperationException(e);
}
}

public static String toStr(Object t) {
try {
return jsonMapper.writeValueAsString(t);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}

Redission分布式锁

依赖

1
2
3
4
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
</dependency>

配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RedissonConfig {
@Autowired
private RedisProperties redisProperties;

@Bean
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://" + redisProperties.getHost() + ":" + redisProperties.getPort())
.setPassword(redisProperties.getPassword())
.setDatabase(redisProperties.getDatabase());
return Redisson.create(config);
}
}

代码实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Autowired
private RedissonClient redissonClient;

public <T> T executeWithLockThrows(String key, int waitTime, TimeUnit unit, SupplierThrow<T> supplier) throws Throwable {
RLock lock = redissonClient.getLock(key);
boolean lockSuccess = lock.tryLock(waitTime, unit);
if (!lockSuccess) {
throw new BusinessException(CommonErrorEnum.LOCK_LIMIT);
}
try {
return supplier.get();//执行锁内的代码逻辑
} finally {
lock.unlock();
}
}

详情见[分布式锁封装 | Calyee`Blog](https://blog.calyee.top/2024/03/13/分布式锁封装/)

BeanCopyUtils

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.List;
import java.util.stream.Collectors;

/**
* @ClassName BeanCopyUtils
* @Description 泛型
* @Author QiuLiHang
* @DATE 2023/8/4 18:51
* @Version 1.0
*/

public class BeanCopyUtils {

private BeanCopyUtils() {
}

/**
* 减少了自己创建的步骤
* @param source 要拷贝属性的源对象
* @param clazz 目标对象的类类型,用于创建目标对象实例(字节码对象)
* @return 目标对象实例,其属性已经拷贝了源对象的属性
* @param <V>
*/
public static <V> V copyBean(Object source,Class<V> clazz) {
//创建目标对象
V result = null;
try {
// 该方法首先使用Java的反射机制创建一个目标对象
result = clazz.newInstance();
//实现属性copy
BeanUtils.copyProperties(source, result);
} catch (Exception e) {
e.printStackTrace();
}
//返回结果
return result;
}

/**
*
* @param list 源对象列表,其中每个元素都是源对象
* @param clazz 目标对象的类类型,用于创建目标对象实例
* @return 包含目标对象的新列表
* @param <O>
* @param <V>
*/
public static <O,V> List<V> copyBeanList(List<O> list, Class<V> clazz){
return list.stream()
.map(o -> copyBean(o, clazz))
.collect(Collectors.toList());
}
}

JwtUtil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* JWT工具类
*/
public class JwtUtil {

//有效期为
public static final Long JWT_TTL = 24*60 * 60 *1000L;// 60 * 60 *1000 一个小时
//设置秘钥明文
public static final String JWT_KEY = "qiulihang";

public static String getUUID(){
String token = UUID.randomUUID().toString().replaceAll("-", "");
return token;
}

/**
* 生成jtw
* @param subject token中要存放的数据(json格式)
* @return
*/
public static String createJWT(String subject) {
JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
return builder.compact();
}

/**
* 生成jtw
* @param subject token中要存放的数据(json格式)
* @param ttlMillis token超时时间
* @return
*/
public static String createJWT(String subject, Long ttlMillis) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
return builder.compact();
}

private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
SecretKey secretKey = generalKey();
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
if(ttlMillis==null){
ttlMillis=JwtUtil.JWT_TTL;
}
long expMillis = nowMillis + ttlMillis;
Date expDate = new Date(expMillis);
return Jwts.builder()
.setId(uuid) //唯一的ID
.setSubject(subject) // 主题 可以是JSON数据
.setIssuer("qlh") // 签发者
.setIssuedAt(now) // 签发时间
.signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
.setExpiration(expDate);
}

/**
* 创建token
* @param id
* @param subject
* @param ttlMillis
* @return
*/
public static String createJWT(String id, String subject, Long ttlMillis) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
return builder.compact();
}

public static void main(String[] args) throws Exception {
String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJjYWM2ZDVhZi1mNjVlLTQ0MDAtYjcxMi0zYWEwOGIyOTIwYjQiLCJzdWIiOiJzZyIsImlzcyI6InNnIiwiaWF0IjoxNjM4MTA2NzEyLCJleHAiOjE2MzgxMTAzMTJ9.JVsSbkP94wuczb4QryQbAke3ysBDIL5ou8fWsbt_ebg";
Claims claims = parseJWT(token);
System.out.println(claims);
}

/**
* 生成加密后的秘钥 secretKey
* @return
*/
public static SecretKey generalKey() {
byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}

/**
* 解析
*
* @param jwt
* @return
* @throws Exception
*/
public static Claims parseJWT(String jwt) throws Exception {
SecretKey secretKey = generalKey();
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(jwt)
.getBody();
}

}

业务校验工具 AssertUtil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import cn.hutool.core.util.ObjectUtil;
import org.hibernate.validator.HibernateValidator;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.text.MessageFormat;
import java.util.*;

/**
* 校验工具类
*/
public class AssertUtil {

/**
* 校验到失败就结束
*/
private static Validator failFastValidator = Validation.byProvider(HibernateValidator.class)
.configure()
.failFast(true)
.buildValidatorFactory().getValidator();

/**
* 全部校验
*/
private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

/**
* 注解验证参数(校验到失败就结束)
*
* @param obj
*/
public static <T> void fastFailValidate(T obj) {
Set<ConstraintViolation<T>> constraintViolations = failFastValidator.validate(obj);
if (constraintViolations.size() > 0) {
throwException(CommonErrorEnum.PARAM_INVALID, constraintViolations.iterator().next().getMessage());
}
}

/**
* 注解验证参数(全部校验,抛出异常)
*
* @param obj
*/
public static <T> void allCheckValidateThrow(T obj) {
Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
if (constraintViolations.size() > 0) {
StringBuilder errorMsg = new StringBuilder();
Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
while (iterator.hasNext()) {
ConstraintViolation<T> violation = iterator.next();
//拼接异常信息
errorMsg.append(violation.getPropertyPath().toString()).append(":").append(violation.getMessage()).append(",");
}
//去掉最后一个逗号
throwException(CommonErrorEnum.PARAM_INVALID, errorMsg.toString().substring(0, errorMsg.length() - 1));
}
}


/**
* 注解验证参数(全部校验,返回异常信息集合)
*
* @param obj
*/
public static <T> Map<String, String> allCheckValidate(T obj) {
Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
if (constraintViolations.size() > 0) {
Map<String, String> errorMessages = new HashMap<>();
Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
while (iterator.hasNext()) {
ConstraintViolation<T> violation = iterator.next();
errorMessages.put(violation.getPropertyPath().toString(), violation.getMessage());
}
return errorMessages;
}
return new HashMap<>();
}

//如果不是true,则抛异常
public static void isTrue(boolean expression, String msg) {
if (!expression) {
throwException(msg);
}
}

public static void isTrue(boolean expression, ErrorEnum errorEnum, Object... args) {
if (!expression) {
throwException(errorEnum, args);
}
}

//如果是true,则抛异常
public static void isFalse(boolean expression, String msg) {
if (expression) {
throwException(msg);
}
}

//如果是true,则抛异常
public static void isFalse(boolean expression, ErrorEnum errorEnum, Object... args) {
if (expression) {
throwException(errorEnum, args);
}
}

//如果不是非空对象,则抛异常
public static void isNotEmpty(Object obj, String msg) {
if (isEmpty(obj)) {
throwException(msg);
}
}

//如果不是非空对象,则抛异常
public static void isNotEmpty(Object obj, ErrorEnum errorEnum, Object... args) {
if (isEmpty(obj)) {
throwException(errorEnum, args);
}
}

//如果不是非空对象,则抛异常
public static void isEmpty(Object obj, String msg) {
if (!isEmpty(obj)) {
throwException(msg);
}
}

public static void equal(Object o1, Object o2, String msg) {
if (!ObjectUtil.equal(o1, o2)) {
throwException(msg);
}
}

public static void notEqual(Object o1, Object o2, String msg) {
if (ObjectUtil.equal(o1, o2)) {
throwException(msg);
}
}

private static boolean isEmpty(Object obj) {
return ObjectUtil.isEmpty(obj);
}

private static void throwException(String msg) {
throwException(null, msg);
}

private static void throwException(ErrorEnum errorEnum, Object... arg) {
if (Objects.isNull(errorEnum)) {
errorEnum = CommonErrorEnum.BUSINESS_ERROR;
}
throw new BusinessException(errorEnum.getErrorCode(), MessageFormat.format(errorEnum.getErrorMsg(), arg));
}

}

上述工具还需要配合下面的三个类使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @author: Caluee
* @description: 自定义义务异常
*/
@Data
public class BusinessException extends RuntimeException {
protected Integer errorCode;
protected String errorMsg;

public BusinessException(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
this.errorCode = CommonErrorEnum.BUSINESS_ERROR.getErrorCode();
}
public BusinessException(String errorMsg, Integer errorCode) {
super(errorMsg);
this.errorMsg = errorMsg;
this.errorCode = errorCode;
}
}
1
2
3
4
5
6
7
8
/**
* @author: Caluee
* @description: 定义错误规范
*/
public interface ErrorEnum {
Integer getErrorCode();
String getErrorMsg();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* @author: Caluee
* @description: 全局异常参数定义
*/
@AllArgsConstructor
@Getter
public enum CommonErrorEnum implements ErrorEnum{
BUSINESS_ERROR(0, "{0}"),
PARAM_INVALID(-2, "参数校验失败"),
SYSTEM_ERROR(-1, "系统出小差了,请稍后再试"), // 业务异常 >1
;
private final Integer code;
private final String msg;

@Override
public Integer getErrorCode() {
return code;
}
@Override
public String getErrorMsg() {
return msg;
}
}

全局异常处理

基于上述的三个异常类, 我们需要引入全局异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* @author: Caluee
* @description: 全局异常处理
*/
@Slf4j
@RestControllerAdvice //对所有的controller出来的异常都会通知
public class GlobalExceptionHandler {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ApiResult<?> methodArgumentNotValidException(MethodArgumentNotValidException e) {
StrBuilder errorMsg = new StrBuilder();
for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
errorMsg.append(fieldError.getField())
.append(fieldError.getDefaultMessage())
.append(",");
}
String errRes = errorMsg.toString().substring(0, errorMsg.length() - 1); // 去除最后的逗号
return ApiResult.fail(CommonErrorEnum.PARAM_INVALID.getCode(), errRes);
}

/**
* 业务异常
*
* @param e
* @return
*/
@ExceptionHandler(value = BusinessException.class)
public ApiResult<?> businessException(BusinessException e) {
log.info("business exception! The reason is:{}", e.getMessage());
return ApiResult.fail(e.getErrorCode(), e.getErrorMsg());
}

/**
* 最后的防线 顶级异常处理
*
* @param e
* @return
*/
@ExceptionHandler(value = Throwable.class)
public ApiResult<?> throwable(Throwable e) {
log.error("system exception! The reason is:{}", e.getMessage());
return ApiResult.fail(CommonErrorEnum.SYSTEM_ERROR);
}
}

本地缓存配置

本地缓存用于不需要经常做变化的数据,如果需要中心化的则使用Redis

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.concurrent.TimeUnit;

@EnableCaching
@Configuration
public class CacheConfig extends CachingConfigurerSupport {

@Bean("caffeineCacheManager")
@Primary
public CacheManager caffeineCacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
// 方案一(常用):定制化缓存Cache
cacheManager.setCaffeine(Caffeine.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.initialCapacity(100)
.maximumSize(200));
return cacheManager;
}
}

使用则在方法上加注解@Cachable即可