利用GSON把map转换成string

1
2
3
Map<String, String> params;
Gson gson = new Gson();
String json = gson.toJson(params, HashMap.class);

把String转换成Map

1
2
3
String plainText;
Gson gson = new Gson();
HashMap plainTextMap = gson.fromJson(plainText, HashMap.class);

new线程休眠时间

1
2
//休息5秒
TimeUnit.SECONDS.sleep(5);

可重入锁–并发锁的添加(当程序多线程执行时给当前线程加一把锁)

1
2
3
4
5
6
7
8
9
10
11
//new可重入锁(和synchronized同步锁区别:ReentrantLock锁可以重复进入,当已有程序进
//入则自动跳过synchronized锁会让程序等待当前线程执行完毕才能执行)
private final ReentrantLock lock = new ReentrantLock();

if(lock.tryLock()){
try{
//业务处理
} finally {
lock.unlock();
}
}

动态日期处理(几分钟之前)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//日期没有处理前
@GetMapping("/demo")
public R test(){
//五分钟之前(和北京时间差8小时)
Instant now = Instant.now().minus(Duration.ofMinutes(5));
return R.ok().data("msg","测试demo").data("now",new Date()).data("date",now);
}
//输出结果
{"code":0,"msg":"成功","data":{"msg":"测试demo","date":"2022-11-18T08:07:39.330Z","now":"2022-11-18T16:07:39.330+0800"}}
//配置文件加入
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
//输出结果
{"code":0,"msg":"成功","data":{"msg":"测试demo","date":"2022-11-18T08:16:37.075Z","now":"2022-11-18 16:16:37"}}

{"code":0,"msg":"成功","data":{"aa":11,"aa1":112}}