|
@@ -0,0 +1,63 @@
|
|
|
+//封装AssessToken服务类
|
|
|
+package cn.hnthyy.thmz.service.impl.his.jy;
|
|
|
+
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
+import org.springframework.data.redis.core.RedisTemplate;
|
|
|
+import org.springframework.http.HttpStatus;
|
|
|
+import org.springframework.http.ResponseEntity;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+import org.springframework.web.client.RestTemplate;
|
|
|
+
|
|
|
+import javax.annotation.Resource;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+@Service
|
|
|
+public class AssessTokenService {
|
|
|
+ @Value("http://20.46.201.94:9999/auth/accesstoken/create?appId=saca_ivA9ipRTKJ&appSecret=YXCxOq4DUMuFfFrPs9dFKXPKT0PSjWzY")
|
|
|
+ private String tokenUrl;
|
|
|
+ @Value("saca_ivA9ipRTKJ")
|
|
|
+ private String appId;
|
|
|
+ @Value("YXCxOq4DUMuFfFrPs9dFKXPKT0PSjWzY")
|
|
|
+ private String appSecret;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private RedisTemplate<String, AccessToken> redisTemplate;
|
|
|
+
|
|
|
+
|
|
|
+ private static final String TOKEN_KEY = "access_token";
|
|
|
+
|
|
|
+ // 获取新 Token(调用认证接口)
|
|
|
+ public AccessToken fetchNewToken() {
|
|
|
+ RestTemplate restTemplate = new RestTemplate();
|
|
|
+ Map<String, String> params = new HashMap<>();
|
|
|
+ params.put("grant_type", "client_credential");
|
|
|
+ params.put("appid", appId);
|
|
|
+ params.put("secret", appSecret);
|
|
|
+
|
|
|
+ ResponseEntity<Map> response = restTemplate.getForEntity(
|
|
|
+ tokenUrl + "?grant_type={grant_type}&appid={appid}&secret={secret}",
|
|
|
+ Map.class,
|
|
|
+ params
|
|
|
+ );
|
|
|
+
|
|
|
+ if (response.getStatusCode() == HttpStatus.OK) {
|
|
|
+ Map<String, Object> body = response.getBody();
|
|
|
+ String token = (String) body.get("access_token");
|
|
|
+ int expiresIn = (int) body.get("expires_in");
|
|
|
+ long expiresAt = System.currentTimeMillis() / 1000 + expiresIn - 300; // 提前5分钟过期
|
|
|
+ return new AccessToken(token, expiresAt);
|
|
|
+ }
|
|
|
+ throw new RuntimeException("Failed to fetch token");
|
|
|
+ }
|
|
|
+
|
|
|
+ // 存储 Token 到 Redis
|
|
|
+ public void storeToken(AccessToken token) {
|
|
|
+ redisTemplate.opsForValue().set(TOKEN_KEY, token);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 从 Redis 获取 Token
|
|
|
+ public AccessToken getToken() {
|
|
|
+ return redisTemplate.opsForValue().get(TOKEN_KEY);
|
|
|
+ }
|
|
|
+}
|