JAVA常用语法和函数
常用函数对象
String.valueOf():用于将任意类型数据转为字符串;
Duration:是专门表示「时间间隔 / 时长」的类,例如:Duration.ofHours(1)表示1小时、Duration.ofMinutes(30)表示30分钟、……、Duration.ofHours(1).getSeconds()获取1小时对应的秒数;
ConcurrentHashMap
ConcurrentHashMap 是线程安全的 Map,在多线程场景下可确保数据安全;ConcurrentHashMap 有一个 computeIfAbsent 函数,可在 key 不存在保存值, key 已存在时直接返回已有值;如下:
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
String value = map.computeIfAbsent(
"name",
key -> "Tom"
);
System.out.println(value);
formatted 字符串格式化
与 C 语言中的 printf 语法相似,其作用不仅仅是拼接字符串,它还能对字符串进行格式化、类型转换等;
# 简单替换 — 看起来像拼接
"%s".formatted("hello") // "hello"
# 类型转换 — 拼接做不到
"数量: %d".formatted(42) ## "数量: 42"(int → String)
"价格: %.2f".formatted(99.999) ## "价格: 99.99"(精度控制)
"进度: %d%%".formatted(75) ## "进度: 75%"(%% 转义为 %)
# 宽度与对齐 — 拼接做不到
"|%10s|".formatted("hi") ## "| hi|"(右对齐,宽度10)
"|%10d|".formatted(42) ## "| 42|"
"|%s %s %s|".formatted("a", "b", "c") ## "|a b c|"(多占位符)
# 进制转换
"十六进制: %x".formatted(255) ## "十六进制: ff"
"八进制: %o".formatted(8) ## "八进制: 10"
Redis Lua 脚本
Redis 是单线程串行执行,而 Lua 脚本作为一个整体执行,执行期间不会被其他命令插入,因此其具备原子性,适用于需要多个 Redis 操作保持一致性的场景。例如下:
## 定义 Lua 脚本(用于计算)
private static final DefaultRedisScript<Long> HOURLY_LIMIT_SCRIPT = new DefaultRedisScript<>(
"""
local current = redis.call('GET', KEYS[1]) ## 获取 key 对应的值
if current and tonumber(current) >= tonumber(ARGV[1]) then ## 如果 key 对应的值大于等于传入的参数1,则返回 -1 (tonumber用于将值转为数)
return -1
end
if current then
return redis.call('INCR', KEYS[1]) ## 如果计数存在,则自增
else
redis.call('SET', KEYS[1], 1, 'EX', ARGV[2]) ## 如果计数不存在,则创建;同过参数2设置此 key 的有效期
return 1
end
""",
Long.class);
## 执行脚本
Long result = stringRedisTemplate.execute(HOURLY_LIMIT_SCRIPT,
List.of(key),
String.valueOf(MAX_HOURLY_SEND_COUNT),
String.valueOf(Duration.ofHours(1).getSeconds()));
execute 函数的定义为:execute(Lua脚本, 要操作的数据 Key, ...args);在 Lua 脚本中的通过 KEYS[1] 来取传入的 数据key,通过 ARGV 来取 args 序列中的参数。