From d72310a838d7f17e596249ab36893b64f7f4c04a Mon Sep 17 00:00:00 2001 From: CangJieStore Date: Thu, 12 Nov 2026 21:21:51 +0800 Subject: [PATCH] etcd --- .workbuddy/memory/2026-11-04.md | 12 ++ simple-starter-bom/pom.xml | 6 + simple-starter-captcha/pom.xml | 1 + .../simple-starter-captcha-tianai/pom.xml | 33 +++++ .../TianaiCaptchaAutoConfiguration.java | 110 +++++++++++++++ .../TianaiCaptchaProperties.java | 125 ++++++++++++++++++ .../TianaiCaptchaCacheAutoConfiguration.java | 113 ++++++++++++++++ .../cache/TianaiRedisCacheStore.java | 123 +++++++++++++++++ .../captcha/tianai/enums/StorageType.java | 40 ++++++ ...ot.autoconfigure.AutoConfiguration.imports | 2 + .../GrpcEtcdClientAutoConfiguration.java | 9 +- .../starter/grpc/etcd/EtcdNameResolver.java | 27 ++++ .../http/registry/EtcdClientFactory.java | 4 + .../core/constant/PropertiesConstants.java | 5 + simple-starter-dependencies/pom.xml | 8 ++ .../mvc/WebMvcAutoConfiguration.java | 20 +++ 16 files changed, 637 insertions(+), 1 deletion(-) create mode 100644 .workbuddy/memory/2026-11-04.md create mode 100644 simple-starter-captcha/simple-starter-captcha-tianai/pom.xml create mode 100644 simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/TianaiCaptchaAutoConfiguration.java create mode 100644 simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/TianaiCaptchaProperties.java create mode 100644 simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/cache/TianaiCaptchaCacheAutoConfiguration.java create mode 100644 simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/cache/TianaiRedisCacheStore.java create mode 100644 simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/enums/StorageType.java create mode 100644 simple-starter-captcha/simple-starter-captcha-tianai/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports diff --git a/.workbuddy/memory/2026-11-04.md b/.workbuddy/memory/2026-11-04.md new file mode 100644 index 0000000..7a1d25c --- /dev/null +++ b/.workbuddy/memory/2026-11-04.md @@ -0,0 +1,12 @@ +# 2026-11-04 + +## simple-starter 新增 tianai-captcha 验证码模块 + +- 新增子模块 `simple-starter-captcha/simple-starter-captcha-tianai`(artifactId `simple-starter-captcha-tianai`),与现有 `-graphic`(easy-captcha)、`-behavior`(AJ-Captcha)并列。 +- 依赖 `cloud.tianai.captcha:tianai-captcha:1.5.6` 核心库(**不用官方 springboot-starter**,其基于 Spring Boot 2.2/javax,与项目 SB3 不兼容),`simple-starter-cache-redisson` 为 optional。 +- 代码结构:`reliable.simple.starter.captcha.tianai.{autoconfigure, autoconfigure.cache, enums}`;Properties 前缀 `simple-starter.captcha.tianai`(`PropertiesConstants.CAPTCHA_TIANAI` 新增)。 +- 热插拔:`enabled` 默认 false,需显式 `simple-starter.captcha.tianai.enabled=true` 才装配,可与 behavior 模块共存互不干扰。 +- 缓存:`cache-type = default | redis | custom`;Redis 适配 `TianaiRedisCacheStore`(JSON 字符串存储,规避 Redisson TypedJsonJackson3Codec 反序列化丢失 AnyMap 类型)。 +- 版本管理加在 `simple-starter-dependencies`(`tianai-captcha.version`),BOM 增加 artifact。 +- 实测结论:`addDefaultTemplate()` 只注册模板不含底图,必须额外 `addResource(type, classpath:META-INF/cut-image/resource/1.jpg)`;内置模板仅覆盖 SLIDER / ROTATE,CONCAT / WORD_IMAGE_CLICK 需自备模板与底图。 +- 验证:`mvn -pl ... -am compile` 与全量 `mvn -DskipTests compile` 均通过;冒烟测试 SLIDER、ROTATE 生成成功,错误轨迹校验正常返回失败。 diff --git a/simple-starter-bom/pom.xml b/simple-starter-bom/pom.xml index 31d4272..e996cf5 100644 --- a/simple-starter-bom/pom.xml +++ b/simple-starter-bom/pom.xml @@ -146,6 +146,12 @@ simple-starter-captcha-behavior ${revision} + + + reliable.simple.starter + simple-starter-captcha-tianai + ${revision} + diff --git a/simple-starter-captcha/pom.xml b/simple-starter-captcha/pom.xml index 1a9741f..accd530 100644 --- a/simple-starter-captcha/pom.xml +++ b/simple-starter-captcha/pom.xml @@ -19,6 +19,7 @@ simple-starter-captcha-graphic simple-starter-captcha-behavior + simple-starter-captcha-tianai diff --git a/simple-starter-captcha/simple-starter-captcha-tianai/pom.xml b/simple-starter-captcha/simple-starter-captcha-tianai/pom.xml new file mode 100644 index 0000000..2fb2c41 --- /dev/null +++ b/simple-starter-captcha/simple-starter-captcha-tianai/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + + reliable.simple.starter + simple-starter-captcha + ${revision} + ../pom.xml + + + simple-starter-captcha-tianai + jar + + ${project.artifactId} + 验证码模块 - 行为验证码(天爱 tianai-captcha,支持滑块/旋转/滑动还原/文字点选等) + + + + + cloud.tianai.captcha + tianai-captcha + + + + + reliable.simple.starter + simple-starter-cache-redisson + true + + + diff --git a/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/TianaiCaptchaAutoConfiguration.java b/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/TianaiCaptchaAutoConfiguration.java new file mode 100644 index 0000000..16e3b6d --- /dev/null +++ b/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/TianaiCaptchaAutoConfiguration.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2022-present Xcynet Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package reliable.simple.starter.captcha.tianai.autoconfigure; + +import cloud.tianai.captcha.application.ImageCaptchaApplication; +import cloud.tianai.captcha.application.ImageCaptchaProperties; +import cloud.tianai.captcha.application.TACBuilder; +import cloud.tianai.captcha.cache.CacheStore; +import cloud.tianai.captcha.common.constant.CaptchaTypeConstant; +import cloud.tianai.captcha.resource.common.model.dto.Resource; +import cn.hutool.core.collection.CollectionUtil; +import jakarta.annotation.PostConstruct; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import reliable.simple.starter.captcha.tianai.autoconfigure.cache.TianaiCaptchaCacheAutoConfiguration; +import reliable.simple.starter.core.constant.PropertiesConstants; +import reliable.simple.starter.core.constant.StringConstants; + +import java.util.LinkedHashMap; + +/** + * 天爱验证码自动配置 + * + * @author Copyright with xcynet + */ +@AutoConfiguration(after = TianaiCaptchaCacheAutoConfiguration.class) +@ConditionalOnClass(ImageCaptchaApplication.class) +@EnableConfigurationProperties(TianaiCaptchaProperties.class) +@ConditionalOnProperty(prefix = PropertiesConstants.CAPTCHA_TIANAI, name = PropertiesConstants.ENABLED, havingValue = "true") +public class TianaiCaptchaAutoConfiguration { + + private static final Logger log = LoggerFactory.getLogger(TianaiCaptchaAutoConfiguration.class); + + /** + * 内置底图(tianai-captcha 自带,未配置自定义底图时使用) + */ + private static final String DEFAULT_BACKGROUND_IMAGE = "META-INF/cut-image/resource/1.jpg"; + + /** + * 内置模板支持的验证码类型(其余类型需自行提供模板与底图) + */ + private static final String[] DEFAULT_TEMPLATE_TYPES = {CaptchaTypeConstant.SLIDER, CaptchaTypeConstant.ROTATE}; + + /** + * 天爱验证码应用 + * + * @param properties 天爱验证码配置属性 + * @param cacheStore 验证码缓存 + * @return 验证码应用 + */ + @Bean(destroyMethod = "close") + @ConditionalOnMissingBean + public ImageCaptchaApplication imageCaptchaApplication(TianaiCaptchaProperties properties, CacheStore cacheStore) { + TACBuilder builder = TACBuilder.builder() + .setProp(buildApplicationProperties(properties)) + .setCacheStore(cacheStore) + .addDefaultTemplate(); + // 自定义底图 + properties.getBackgroundImages() + .forEach((type, paths) -> paths.forEach(path -> builder + .addResource(type, new Resource("classpath", path)))); + // 未配置自定义底图的类型,回退到内置底图 + for (String type : DEFAULT_TEMPLATE_TYPES) { + if (CollectionUtil.isEmpty(properties.getBackgroundImages().get(type))) { + builder.addResource(type, new Resource("classpath", DEFAULT_BACKGROUND_IMAGE)); + } + } + // 自定义字体(文字点选验证码使用) + properties.getFonts().forEach(path -> builder.addFont(new Resource("classpath", path))); + return builder.build(); + } + + /** + * 构建 tianai-captcha 应用配置 + * + * @param properties 天爱验证码配置属性 + * @return 应用配置 + */ + private static ImageCaptchaProperties buildApplicationProperties(TianaiCaptchaProperties properties) { + ImageCaptchaProperties applicationProperties = new ImageCaptchaProperties(); + applicationProperties.setPrefix(properties.getPrefix()); + applicationProperties.setExpire(new LinkedHashMap<>(properties.getExpire())); + return applicationProperties; + } + + @PostConstruct + public void postConstruct() { + log.debug(StringConstants.LOGGER + " - Auto Configuration 'Captcha-Tianai' completed initialization."); + } +} diff --git a/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/TianaiCaptchaProperties.java b/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/TianaiCaptchaProperties.java new file mode 100644 index 0000000..fa40708 --- /dev/null +++ b/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/TianaiCaptchaProperties.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2022-present Xcynet Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package reliable.simple.starter.captcha.tianai.autoconfigure; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import reliable.simple.starter.captcha.tianai.enums.StorageType; +import reliable.simple.starter.core.constant.PropertiesConstants; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 天爱验证码配置属性 + * + *

热插拔:默认关闭,引入依赖后需显式配置 {@code simple-starter.captcha.tianai.enabled=true} 才会装配, + * 可与 {@code simple-starter-captcha-behavior}(AJ-Captcha)同时存在于类路径而互不干扰。

+ * + * @author Copyright with xcynet + */ +@ConfigurationProperties(PropertiesConstants.CAPTCHA_TIANAI) +public class TianaiCaptchaProperties { + + /** + * 是否启用(默认:false,按需开启实现热插拔) + */ + private boolean enabled = false; + + /** + * 缓存类型(默认:内存) + */ + private StorageType cacheType = StorageType.DEFAULT; + + /** + * 缓存键前缀(默认:captcha:tianai) + */ + private String prefix = "captcha:tianai"; + + /** + * 验证码有效期(单位:毫秒,键为验证码类型,default 为全局默认值) + */ + private Map expire = defaultExpire(); + + /** + * 自定义底图(键为验证码类型,如 SLIDER / ROTATE / CONCAT / WORD_IMAGE_CLICK,值为 classpath 下的图片路径) + * + *

不配置则使用 tianai-captcha 内置底图

+ */ + private Map> backgroundImages = new LinkedHashMap<>(); + + /** + * 自定义字体(classpath 下的字体路径,如 font/SimHei.ttf,用于文字点选验证码) + */ + private List fonts = new ArrayList<>(); + + private static Map defaultExpire() { + Map expire = new LinkedHashMap<>(); + expire.put("default", 120_000L); + expire.put("WORD_IMAGE_CLICK", 200_000L); + return expire; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public StorageType getCacheType() { + return cacheType; + } + + public void setCacheType(StorageType cacheType) { + this.cacheType = cacheType; + } + + public String getPrefix() { + return prefix; + } + + public void setPrefix(String prefix) { + this.prefix = prefix; + } + + public Map getExpire() { + return expire; + } + + public void setExpire(Map expire) { + this.expire = expire; + } + + public Map> getBackgroundImages() { + return backgroundImages; + } + + public void setBackgroundImages(Map> backgroundImages) { + this.backgroundImages = backgroundImages; + } + + public List getFonts() { + return fonts; + } + + public void setFonts(List fonts) { + this.fonts = fonts; + } +} diff --git a/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/cache/TianaiCaptchaCacheAutoConfiguration.java b/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/cache/TianaiCaptchaCacheAutoConfiguration.java new file mode 100644 index 0000000..bb6a557 --- /dev/null +++ b/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/cache/TianaiCaptchaCacheAutoConfiguration.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2022-present Xcynet Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package reliable.simple.starter.captcha.tianai.autoconfigure.cache; + +import cloud.tianai.captcha.cache.CacheStore; +import cloud.tianai.captcha.cache.impl.LocalCacheStore; +import jakarta.annotation.PostConstruct; +import org.redisson.client.RedisClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.core.ResolvableType; +import reliable.simple.starter.cache.redisson.autoconfigure.RedissonAutoConfiguration; +import reliable.simple.starter.captcha.tianai.autoconfigure.TianaiCaptchaProperties; +import reliable.simple.starter.core.constant.PropertiesConstants; +import reliable.simple.starter.core.constant.StringConstants; + +/** + * 天爱验证码缓存自动配置 + * + * @author Copyright with xcynet + */ +@AutoConfiguration +@ConditionalOnClass(CacheStore.class) +@ConditionalOnProperty(prefix = PropertiesConstants.CAPTCHA_TIANAI, name = PropertiesConstants.ENABLED, havingValue = "true") +public class TianaiCaptchaCacheAutoConfiguration { + + private static final Logger log = LoggerFactory.getLogger(TianaiCaptchaCacheAutoConfiguration.class); + + private TianaiCaptchaCacheAutoConfiguration() { + } + + /** + * 自定义缓存实现-默认(内存) + */ + @AutoConfiguration + @ConditionalOnMissingBean(CacheStore.class) + @ConditionalOnProperty(prefix = PropertiesConstants.CAPTCHA_TIANAI, name = "cache-type", havingValue = "default", matchIfMissing = true) + public static class Default { + + @Bean + public CacheStore cacheStore() { + return new LocalCacheStore(); + } + + @PostConstruct + public void postConstruct() { + log.debug(StringConstants.LOGGER + " - Auto Configuration 'Captcha-Tianai-Cache-Default' completed initialization."); + } + } + + /** + * 自定义缓存实现-Redis + */ + @AutoConfiguration(after = RedissonAutoConfiguration.class) + @ConditionalOnClass(RedisClient.class) + @ConditionalOnMissingBean(CacheStore.class) + @ConditionalOnProperty(prefix = PropertiesConstants.CAPTCHA_TIANAI, name = "cache-type", havingValue = "redis") + public static class Redis { + + @Bean + public CacheStore cacheStore(TianaiCaptchaProperties properties) { + return new TianaiRedisCacheStore(properties.getPrefix()); + } + + @PostConstruct + public void postConstruct() { + log.debug(StringConstants.LOGGER + " - Auto Configuration 'Captcha-Tianai-Cache-Redis' completed initialization."); + } + } + + /** + * 自定义缓存实现 + */ + @AutoConfiguration + @ConditionalOnProperty(prefix = PropertiesConstants.CAPTCHA_TIANAI, name = "cache-type", havingValue = "custom") + public static class Custom { + + @Bean + @ConditionalOnMissingBean + public CacheStore cacheStore() { + if (log.isErrorEnabled()) { + log.error("Consider defining a bean of type '{}' in your configuration.", ResolvableType + .forClass(CacheStore.class)); + } + throw new NoSuchBeanDefinitionException(CacheStore.class); + } + + @PostConstruct + public void postConstruct() { + log.debug(StringConstants.LOGGER + " - Auto Configuration 'Captcha-Tianai-Cache-Custom' completed initialization."); + } + } +} diff --git a/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/cache/TianaiRedisCacheStore.java b/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/cache/TianaiRedisCacheStore.java new file mode 100644 index 0000000..4060113 --- /dev/null +++ b/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/autoconfigure/cache/TianaiRedisCacheStore.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2022-present Xcynet Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package reliable.simple.starter.captcha.tianai.autoconfigure.cache; + +import cn.hutool.core.text.CharSequenceUtil; +import cn.hutool.json.JSONUtil; +import cloud.tianai.captcha.cache.CacheStore; +import cloud.tianai.captcha.common.AnyMap; +import org.redisson.api.RAtomicLong; +import org.redisson.api.RBucket; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reliable.simple.starter.cache.redisson.util.RedisUtils; + +import java.time.Duration; +import java.util.concurrent.TimeUnit; + +/** + * 天爱验证码 Redis 缓存实现 + * + *

验证码数据以 JSON 字符串存储,避免不同 Redisson 编解码器反序列化后丢失 {@link AnyMap} 类型。

+ * + * @author Copyright with xcynet + */ +public class TianaiRedisCacheStore implements CacheStore { + + private static final Logger log = LoggerFactory.getLogger(TianaiRedisCacheStore.class); + + /** + * 默认验证码有效期(单位:毫秒) + */ + private static final long DEFAULT_EXPIRE = 120_000L; + + private final String prefix; + + public TianaiRedisCacheStore(String prefix) { + this.prefix = CharSequenceUtil.addSuffixIfNot(CharSequenceUtil.blankToDefault(prefix, "captcha:tianai"), ":"); + } + + @Override + public AnyMap getCache(String key) { + return parse(RedisUtils.get(formatKey(key))); + } + + @Override + public AnyMap getAndRemoveCache(String key) { + RBucket bucket = RedisUtils.getClient().getBucket(formatKey(key)); + return parse(bucket.getAndDelete()); + } + + @Override + public boolean setCache(String key, AnyMap data, Long expire, TimeUnit timeUnit) { + if (data == null || data.isEmpty()) { + return false; + } + long expireMillis = expire == null || expire <= 0 ? DEFAULT_EXPIRE : timeUnit.toMillis(expire); + RedisUtils.set(formatKey(key), JSONUtil.toJsonStr(data), Duration.ofMillis(expireMillis)); + return true; + } + + @Override + public Long incr(String key, long delta, Long expire, TimeUnit timeUnit) { + RAtomicLong counter = RedisUtils.getClient().getAtomicLong(formatKey(key)); + long value = counter.addAndGet(delta); + if (expire != null && expire > 0) { + counter.expire(Duration.ofMillis(timeUnit.toMillis(expire))); + } + return value; + } + + @Override + public Long getLong(String key) { + RAtomicLong counter = RedisUtils.getClient().getAtomicLong(formatKey(key)); + return counter.isExists() ? counter.get() : null; + } + + @Override + public void close() { + // Redisson 客户端由容器统一管理,此处无需释放资源 + } + + /** + * 拼接完整的缓存键 + * + * @param key 原始键 + * @return 带前缀的缓存键 + */ + private String formatKey(String key) { + return prefix + key; + } + + /** + * 将 JSON 字符串解析为 {@link AnyMap} + * + * @param json JSON 字符串 + * @return 验证码缓存数据,解析失败或内容为空时返回 null + */ + private AnyMap parse(String json) { + if (CharSequenceUtil.isBlank(json)) { + return null; + } + try { + return AnyMap.of(JSONUtil.parseObj(json)); + } catch (Exception e) { + log.warn("天爱验证码缓存数据解析失败", e); + return null; + } + } +} diff --git a/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/enums/StorageType.java b/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/enums/StorageType.java new file mode 100644 index 0000000..398fb62 --- /dev/null +++ b/simple-starter-captcha/simple-starter-captcha-tianai/src/main/java/reliable/simple/starter/captcha/tianai/enums/StorageType.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022-present Xcynet Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package reliable.simple.starter.captcha.tianai.enums; + +/** + * 天爱验证码缓存类型 + * + * @author Copyright with xcynet + */ +public enum StorageType { + + /** + * 默认(内存) + */ + DEFAULT, + + /** + * Redis + */ + REDIS, + + /** + * 自定义 + */ + CUSTOM +} diff --git a/simple-starter-captcha/simple-starter-captcha-tianai/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/simple-starter-captcha/simple-starter-captcha-tianai/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 0000000..88544ca --- /dev/null +++ b/simple-starter-captcha/simple-starter-captcha-tianai/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1,2 @@ +reliable.simple.starter.captcha.tianai.autoconfigure.cache.TianaiCaptchaCacheAutoConfiguration +reliable.simple.starter.captcha.tianai.autoconfigure.TianaiCaptchaAutoConfiguration diff --git a/simple-starter-cluster/simple-starter-cluster-grpc/src/main/java/reliable/simple/starter/grpc/autoconfigure/GrpcEtcdClientAutoConfiguration.java b/simple-starter-cluster/simple-starter-cluster-grpc/src/main/java/reliable/simple/starter/grpc/autoconfigure/GrpcEtcdClientAutoConfiguration.java index cbfb4cc..0c66267 100644 --- a/simple-starter-cluster/simple-starter-cluster-grpc/src/main/java/reliable/simple/starter/grpc/autoconfigure/GrpcEtcdClientAutoConfiguration.java +++ b/simple-starter-cluster/simple-starter-cluster-grpc/src/main/java/reliable/simple/starter/grpc/autoconfigure/GrpcEtcdClientAutoConfiguration.java @@ -19,6 +19,7 @@ package reliable.simple.starter.grpc.autoconfigure; import java.io.FileInputStream; import java.io.InputStream; import java.net.URI; +import java.time.Duration; import java.util.List; import io.etcd.jetcd.ByteSequence; @@ -106,7 +107,13 @@ public class GrpcEtcdClientAutoConfiguration { .password(ByteSequence.from(props.getPassword().getBytes())); } - log.info("etcd client initialized, endpoints={}", endpoints); + // gRPC keepalive:避免 watch 流空闲被中间网络超时掐断,进而频繁重建、加剧 auth token 失效抖动。 + // 10s < 常见 30s 空闲超时,且 >= etcd 默认 grpc-keepalive-min-time(5s)。 + Duration keepaliveTime = Duration.ofSeconds(10); + Duration keepaliveTimeout = Duration.ofSeconds(5); + builder.keepaliveTime(keepaliveTime).keepaliveTimeout(keepaliveTimeout); + + log.info("etcd client initialized (keepalive time={}, timeout={}), endpoints={}", keepaliveTime, keepaliveTimeout, endpoints); return builder.build(); } diff --git a/simple-starter-cluster/simple-starter-cluster-grpc/src/main/java/reliable/simple/starter/grpc/etcd/EtcdNameResolver.java b/simple-starter-cluster/simple-starter-cluster-grpc/src/main/java/reliable/simple/starter/grpc/etcd/EtcdNameResolver.java index 53c4c04..edf55c5 100644 --- a/simple-starter-cluster/simple-starter-cluster-grpc/src/main/java/reliable/simple/starter/grpc/etcd/EtcdNameResolver.java +++ b/simple-starter-cluster/simple-starter-cluster-grpc/src/main/java/reliable/simple/starter/grpc/etcd/EtcdNameResolver.java @@ -212,6 +212,15 @@ public class EtcdNameResolver extends NameResolver { @Override public void onError(Throwable e) { + // jetcd WatchImpl 在 invalid auth token / permission denied 时会 refresh credential 并 + // 自行 reschedule resume。此处若再 close+重建 watcher,会与 jetcd 内部恢复竞态, + // 生产上表现为偶发 Unauthenticated 后地址解析抖动。鉴权类错误只刷新地址,不抢着重启。 + if (isAuthTokenError(e)) { + log.warn("etcd nameResolver watch auth expired, rely on jetcd resume: serviceKey={}, msg={}", serviceKey, e + .getMessage()); + refreshAddressesAsync(); + return; + } log.warn("etcd nameResolver watch error, will restart: serviceKey={}", serviceKey, e); restartWatchWithBackoff(); } @@ -228,6 +237,24 @@ public class EtcdNameResolver extends NameResolver { log.info("etcd nameResolver watch started: serviceKey={}", serviceKey); } + /** + * 是否为 etcd 鉴权 token 失效(jetcd 会自行 refresh + resume)。 + */ + private static boolean isAuthTokenError(Throwable e) { + for (Throwable t = e; t != null; t = t.getCause()) { + String msg = t.getMessage(); + if (msg == null) { + continue; + } + String lower = msg.toLowerCase(); + if (lower.contains("invalid auth token") || lower.contains("unauthenticated") || lower + .contains("permission denied")) { + return true; + } + } + return false; + } + /** * 带指数退避重建 watcher。 * 退避序列:0s/1s/2s/4s/8s/16s,上限 30s。 diff --git a/simple-starter-cluster/simple-starter-cluster-http-registry/src/main/java/reliable/simple/starter/http/registry/EtcdClientFactory.java b/simple-starter-cluster/simple-starter-cluster-http-registry/src/main/java/reliable/simple/starter/http/registry/EtcdClientFactory.java index 644eb92..07c50ce 100644 --- a/simple-starter-cluster/simple-starter-cluster-http-registry/src/main/java/reliable/simple/starter/http/registry/EtcdClientFactory.java +++ b/simple-starter-cluster/simple-starter-cluster-http-registry/src/main/java/reliable/simple/starter/http/registry/EtcdClientFactory.java @@ -18,6 +18,7 @@ package reliable.simple.starter.http.registry; import java.io.File; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.util.List; import javax.net.ssl.SSLException; @@ -77,6 +78,9 @@ public final class EtcdClientFactory { builder.password(ByteSequence.from(props.getPassword(), StandardCharsets.UTF_8)); } + // 与 gRPC 侧 Client 一致:watch/lease 流空闲 keepalive,降低 invalid auth token 抖动 + builder.keepaliveTime(Duration.ofSeconds(10)).keepaliveTimeout(Duration.ofSeconds(5)); + return builder.build(); } diff --git a/simple-starter-core/src/main/java/reliable/simple/starter/core/constant/PropertiesConstants.java b/simple-starter-core/src/main/java/reliable/simple/starter/core/constant/PropertiesConstants.java index 0d27a3d..66e8cbd 100644 --- a/simple-starter-core/src/main/java/reliable/simple/starter/core/constant/PropertiesConstants.java +++ b/simple-starter-core/src/main/java/reliable/simple/starter/core/constant/PropertiesConstants.java @@ -115,6 +115,11 @@ public class PropertiesConstants { */ public static final String CAPTCHA_BEHAVIOR = CAPTCHA + StringConstants.DOT + "behavior"; + /** + * 行为验证码配置(天爱) + */ + public static final String CAPTCHA_TIANAI = CAPTCHA + StringConstants.DOT + "tianai"; + /** * 消息配置 */ diff --git a/simple-starter-dependencies/pom.xml b/simple-starter-dependencies/pom.xml index 85e74fa..cb2448a 100644 --- a/simple-starter-dependencies/pom.xml +++ b/simple-starter-dependencies/pom.xml @@ -44,6 +44,7 @@ 1.4.0 1.6.2 + 1.5.6 2.0.2-incubating @@ -366,6 +367,13 @@ ${easy-captcha.version}
+ + + cloud.tianai.captcha + tianai-captcha + ${tianai-captcha.version} + + commons-beanutils diff --git a/simple-starter-web/src/main/java/reliable/simple/starter/web/autoconfigure/mvc/WebMvcAutoConfiguration.java b/simple-starter-web/src/main/java/reliable/simple/starter/web/autoconfigure/mvc/WebMvcAutoConfiguration.java index 68fc596..5328992 100644 --- a/simple-starter-web/src/main/java/reliable/simple/starter/web/autoconfigure/mvc/WebMvcAutoConfiguration.java +++ b/simple-starter-web/src/main/java/reliable/simple/starter/web/autoconfigure/mvc/WebMvcAutoConfiguration.java @@ -16,11 +16,17 @@ package reliable.simple.starter.web.autoconfigure.mvc; +import java.nio.charset.StandardCharsets; +import java.util.List; + import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.format.FormatterRegistry; +import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; +import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageConverters; +import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import reliable.simple.starter.web.autoconfigure.mvc.converter.BaseEnumConverterFactory; import reliable.simple.starter.web.autoconfigure.mvc.converter.time.DateConverter; @@ -46,6 +52,20 @@ public class WebMvcAutoConfiguration implements WebMvcConfigurer { builder.configureMessageConvertersList(converters -> { converters.removeIf(converter -> converter instanceof ByteArrayHttpMessageConverter); converters.add(0, new ByteArrayHttpMessageConverter()); + // StringHttpMessageConverter 默认支持 */* 且排在 Jackson 前,返回 String 时会抢走 JSON 写出, + // Graceful Response 因此不会把字符串包进 R。收成 text/plain 并移到末尾后,JSON 请求走 Jackson。 + StringHttpMessageConverter stringConverter = null; + for (HttpMessageConverter converter : converters) { + if (converter instanceof StringHttpMessageConverter found) { + stringConverter = found; + break; + } + } + if (stringConverter != null) { + stringConverter.setSupportedMediaTypes(List.of(new MediaType("text", "plain", StandardCharsets.UTF_8))); + converters.remove(stringConverter); + converters.add(stringConverter); + } }); }