TokenController.java 2.2 KB
package com.aukey.example.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.concurrent.TimeUnit;

/**
 * @author: wgf
 * @create: 2020-05-13 10:11
 * @description: 获取token回调controller
 * 当向数据仓库平台发起 http://dw.aukeyit.com/api/authorize?appSecret=应用秘钥 请求时,
 * 数据仓库验证应用秘钥后会生成token,并通过调用APP回调地址将token作为参数返回到客户端
 **/


@RestController
@RequestMapping("/token")
@ApiIgnore
public class TokenController {
    private Logger log = LoggerFactory.getLogger(TokenController.class);

    /**
     * 当前token
     */
    private static String currentToken = "";


    /*********************************************************************
     * 这里的controller path 需要和数据仓库中APP设置的回调地址保持一致。    *
     * 例如APP里回调地址为 http://localhost:8099/token/receive            *
     * TokenJob定时任务定时请求数据仓库获取授权API后                       *
     * 数据仓库回调 http://localhost:8099/token/receive,并且传递token参数 *
     * 获取token后,可以放在 mysql,redis等。这里DEMO取巧放在内存中。        *
     ********************************************************************/
    @PostMapping("/receive")
    public void receive(String token) {
        log.info("获取到远程DW服务回调请求,token:{}", token);
        currentToken = token;
    }

    public static String getCurrentToken() {
        for (int i = 0; i < 5; i++) {
            if (StringUtils.isEmpty(currentToken)) {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                return currentToken;
            }
        }

        return null;
    }
}