Kaynağa Gözat

'检验云accessToken获取与存储'

unknown 3 ay önce
ebeveyn
işleme
ff9aae24ff

+ 0 - 11
pom.xml

@@ -21,17 +21,6 @@
     </properties>
 
     <dependencies>
-        <!-- Spring Data Redis -->
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-data-redis</artifactId>
-        </dependency>
-
-        <!-- 如果使用 Redis 连接池 -->
-        <dependency>
-            <groupId>org.apache.commons</groupId>
-            <artifactId>commons-pool2</artifactId>
-        </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-thymeleaf</artifactId>

+ 7 - 4
src/main/java/cn/hnthyy/thmz/service/impl/his/jy/TokenRefreshScheduler.java → src/main/java/cn/hnthyy/thmz/common/jyYun/TokenRefreshScheduler.java

@@ -1,15 +1,18 @@
 // 配置定时任务刷新 Token
-package cn.hnthyy.thmz.service.impl.his.jy;
+package cn.hnthyy.thmz.common.jyYun;
 
-import org.springframework.beans.factory.annotation.Autowired;
+import cn.hnthyy.thmz.entity.jyYun.AccessToken;
+import cn.hnthyy.thmz.service.his.jyYun.AssessTokenService;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.scheduling.annotation.EnableScheduling;
 import org.springframework.scheduling.annotation.Scheduled;
 
+import javax.annotation.Resource;
+
 @EnableScheduling
 @Configuration
 public class TokenRefreshScheduler {
-    @Autowired
+    @Resource
     private AssessTokenService assessTokenService;
 
     // 每23小时执行一次(早于24小时过期时间)
@@ -17,6 +20,6 @@ public class TokenRefreshScheduler {
     public void refreshToken() {
         AccessToken newToken = assessTokenService.fetchNewToken();
         assessTokenService.storeToken(newToken);
-        System.out.println("Token refreshed: " + newToken.getToken());
+        System.out.println("Token refreshed: " + newToken.getAccessToken());
     }
 }

+ 3 - 2
src/main/java/cn/hnthyy/thmz/service/impl/his/jy/AccessToken.java → src/main/java/cn/hnthyy/thmz/entity/jyYun/AccessToken.java

@@ -1,5 +1,5 @@
 //定义 Token 存储实体
-package cn.hnthyy.thmz.service.impl.his.jy;
+package cn.hnthyy.thmz.entity.jyYun;
 
 import lombok.AllArgsConstructor;
 import lombok.Data;
@@ -9,6 +9,7 @@ import lombok.NoArgsConstructor;
 @AllArgsConstructor
 @NoArgsConstructor
 public class AccessToken {
-    private String token;
+    private String code;
+    private String accessToken;
     private long expiresAt; // 过期时间戳(秒)
 }

+ 31 - 0
src/main/java/cn/hnthyy/thmz/mapper/his/jyYun/AccessTokenMapper.java

@@ -0,0 +1,31 @@
+package cn.hnthyy.thmz.mapper.his.jyYun;
+
+import cn.hnthyy.thmz.entity.jyYun.AccessToken;
+import org.apache.ibatis.annotations.*;
+
+
+/**
+ * 授权码
+ */
+public interface AccessTokenMapper {
+    /**
+     * 查询授权码
+     * @return
+     */
+    @Select("select access_token,expires_at from access_token where code = #{code}")
+    AccessToken selectAccessToken(@Param("code") String code);
+
+    /**
+     * 新增授权码
+     * @return
+     */
+    @Insert("INSERT INTO access_token(code,access_token,expires_at) VALUES (#{code}, #{accessToken}, #{expiresAt})")
+    int insertAccessToken(AccessToken accessToken);
+
+    /**
+     * 更新授权码
+     * @return
+     */
+    @Update("update access_token set code =#{code} ,access_token=#{accessToken},expires_at=#{expiresAt} where code = #{code}")
+    int updateAccessToken(AccessToken accessToken);
+}

+ 4 - 3
src/main/java/cn/hnthyy/thmz/service/impl/his/jy/ApiClient.java → src/main/java/cn/hnthyy/thmz/service/his/jyYun/ApiClient.java

@@ -1,10 +1,11 @@
-package cn.hnthyy.thmz.service.impl.his.jy;
+package cn.hnthyy.thmz.service.his.jyYun;
 
+import cn.hnthyy.thmz.entity.jyYun.AccessToken;
+import org.springframework.boot.web.client.RestTemplateBuilder;
 import org.springframework.context.annotation.Bean;
 import org.springframework.http.*;
 import org.springframework.stereotype.Service;
 import org.springframework.web.client.HttpClientErrorException;
-import org.springframework.boot.web.client.RestTemplateBuilder;
 import org.springframework.web.client.RestTemplate;
 
 import javax.annotation.Resource;
@@ -30,7 +31,7 @@ public class ApiClient {
 
         try {
             HttpHeaders headers = new HttpHeaders();
-            headers.set("Authorization", "Bearer " + token.getToken());
+            headers.set("Authorization", "Bearer " + token.getAccessToken());
             HttpEntity<?> entity = new HttpEntity<>(headers);
 
             ResponseEntity<T> response = restTemplate.exchange(

+ 66 - 0
src/main/java/cn/hnthyy/thmz/service/his/jyYun/AssessTokenService.java

@@ -0,0 +1,66 @@
+//封装AssessToken服务类
+package cn.hnthyy.thmz.service.his.jyYun;
+
+import cn.hnthyy.thmz.entity.jyYun.AccessToken;
+import cn.hnthyy.thmz.service.impl.his.jyYun.AccessTokenImpl;
+import org.springframework.beans.factory.annotation.Value;
+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")
+    private String tokenUrl;
+    @Value("saca_ivA9ipRTKJ")
+    private String appId;
+    @Value("YXCxOq4DUMuFfFrPs9dFKXPKT0PSjWzY")
+    private String appSecret;
+
+    @Resource
+    private AccessTokenImpl accessTokenImpl;
+
+    // 获取新 AccessToken(调用认证接口)
+    public AccessToken fetchNewToken() {
+        RestTemplate restTemplate = new RestTemplate();
+        Map<String, String> params = new HashMap<>();
+        params.put("appId", appId);
+        params.put("appSecret", appSecret);
+
+        ResponseEntity<Map> response = restTemplate.getForEntity(
+                tokenUrl + "?appId={appId}&appSecret={appSecret}",
+                Map.class,
+                params
+        );
+        if (response.getStatusCode() == HttpStatus.OK) {
+            Map<String, Object> body = response.getBody();
+            assert body != null;
+            String accessToken = (String) body.get("access_token");
+            long expiresAt = System.currentTimeMillis() / 1000 + 24 * 60 * 60 - 300; // 提前5分钟过期
+            return new AccessToken("jyYun", accessToken, expiresAt); //检验云
+        }
+        throw new RuntimeException("Failed to fetch accessToken");
+    }
+
+    // 存储 AccessToken
+    public void storeToken(AccessToken accessToken) {
+        AccessToken accessTokenNew = accessTokenImpl.selectAccessToken(accessToken.getCode());
+        if (accessTokenNew == null) {
+            int i = accessTokenImpl.insertAccessToken(accessToken);
+        } else  {
+            accessTokenNew.setAccessToken(accessToken.getAccessToken());
+            accessTokenNew.setExpiresAt(accessToken.getExpiresAt());
+            int i = accessTokenImpl.updateAccessToken(accessTokenNew);
+        }
+    }
+
+    // 获取 AccessToken
+    public AccessToken getToken() {
+        return accessTokenImpl.selectAccessToken("jyYun");
+    }
+}

+ 0 - 63
src/main/java/cn/hnthyy/thmz/service/impl/his/jy/AssessTokenService.java

@@ -1,63 +0,0 @@
-//封装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);
-    }
-}

+ 27 - 0
src/main/java/cn/hnthyy/thmz/service/impl/his/jyYun/AccessTokenImpl.java

@@ -0,0 +1,27 @@
+package cn.hnthyy.thmz.service.impl.his.jyYun;
+
+import cn.hnthyy.thmz.entity.jyYun.AccessToken;
+import cn.hnthyy.thmz.mapper.his.jyYun.AccessTokenMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+
+
+@Service
+@Slf4j
+public class AccessTokenImpl {
+    @SuppressWarnings("all")
+    @Resource
+    private AccessTokenMapper accessTokenMapper;
+
+    public AccessToken selectAccessToken(String code) {
+        return accessTokenMapper.selectAccessToken(code);
+    }
+    public Integer insertAccessToken(AccessToken accessToken) {
+        return accessTokenMapper.insertAccessToken(accessToken);
+    }
+    public Integer updateAccessToken(AccessToken accessToken) {
+        return accessTokenMapper.updateAccessToken(accessToken);
+    }
+}

+ 2 - 1
src/main/java/cn/hnthyy/thmz/service/impl/his/jy/ApiController.java → src/main/java/cn/hnthyy/thmz/service/impl/his/jyYun/ApiController.java

@@ -1,5 +1,6 @@
-package cn.hnthyy.thmz.service.impl.his.jy;
+package cn.hnthyy.thmz.service.impl.his.jyYun;
 
+import cn.hnthyy.thmz.service.his.jyYun.ApiClient;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RequestMapping;

+ 0 - 10
src/main/resources/application-dev.yml

@@ -19,16 +19,6 @@ server:
   servlet:
     context-path: "/thmz"
 spring:
-  redis:
-    host: localhost     # Redis 服务器地址
-    port: 6379         # 默认端口
-    password:          # 密码(若无则省略)
-    database: 0        # 默认数据库索引
-    lettuce:
-      pool:
-        max-active: 8  # 连接池最大连接数
-        max-idle: 4    # 连接池最大空闲连接
-        min-idle: 1    # 连接池最小空闲连接
   #jackson:
     #date-format: "yyyy-MM-dd HH:mm:ss"
     #设置为东八区时间