This commit is contained in:
2026-07-07 15:15:26 +08:00
parent 6380842b34
commit cc5a944b47
5 changed files with 358 additions and 330 deletions
@@ -1,17 +1,7 @@
package com.budwk.app.base.config;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.budwk.app.base.constant.RedisConstant;
import com.budwk.app.base.exception.BaseException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
@@ -33,19 +23,17 @@ public class DataCenterProperties {
@Inject
private PropertiesProxy conf;
@Inject
private RedisService redisService;
private String appId;
private String tokenUrl;
private Map<String, String> codes = new HashMap<>();
private String key;
private String secret;
private Map<String, String> urls = new HashMap<>();
public void init() {
Map<String, String> all = conf.toMap();
appId = all.get("data-center.app-id");
tokenUrl = all.get("data-center.token-url");
extract(all, "data-center.codes.", codes);
key = all.get("data-center.key");
secret = all.get("data-center.secret");
extract(all, "data-center.urls.", urls);
}
@@ -61,59 +49,4 @@ public class DataCenterProperties {
}
});
}
/**
* 读取配置
* @param key 接口类型枚举
* @return 相关配置
*/
public Credential credential(String key) {
String code = codes.get(key);
String url = urls.get(key);
if (code == null || url == null) {
throw new BaseException("未知业务: " + key);
}
String token = getToken(Integer.parseInt(code), key);
return new Credential(url, token);
}
@Getter
@AllArgsConstructor
public static class Credential {
private String url;
private String token;
}
/**
* 获取token
* @param code
* @param keyPrefix
* @return token
*/
private String getToken(Integer code, String keyPrefix) {
String dateCenterPrefix = RedisConstant.DATE_CENTER_PREFIX + keyPrefix;
String token = redisService.get(dateCenterPrefix);
if (StrUtil.isNotBlank(token)) {
return token;
} else {
HttpRequest httpRequest = HttpUtil.createPost(tokenUrl);
Map<String, Object> reqBody = Map.of(
"appId", appId,
"code", code
);
httpRequest.body(JSONUtil.toJsonStr(reqBody));
JSONObject resp = JSONUtil.parseObj(httpRequest.execute().body());
if (resp.getInt("code") != 200) {
throw new BaseException("获取token失败: " + resp.getStr("msg"));
} else {
JSONObject data = resp.getJSONObject("data");
String tokenStr = data.getStr("token");
Integer expire = data.getInt("expire");
redisService.setex(dateCenterPrefix, expire, tokenStr);
return tokenStr;
}
}
}
}