xiaoyong931011
2023-02-23 e3d7ec787c2a2b03af577fa151cf78f951a6ae66
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package cc.mrbird.febs.mall.quartz;
 
import cc.mrbird.febs.common.utils.RedisUtils;
import cc.mrbird.febs.pay.util.WechatConfigure;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
 
import javax.annotation.Resource;
 
@Slf4j
@Component
@ConditionalOnProperty(prefix = "system", name = "job", havingValue = "true")
public class BaiduJob {
 
    @Autowired
    private RedisUtils redisUtils;
    @Resource
    RestTemplate restTemplate;
 
    @Scheduled(cron = "0 0 1 * * ? ")
    public void getAccessToken(){
        // 官网获取的 API Key 更新为你注册的
        String clientId = "MPHXcBxkGLIDOmoaahS9pIB7";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "f5ueNY65fE9C6FzFTVKc6Imo8NdZSWMw";
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + clientId
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + clientSecret;
        String jsonStr = restTemplate.getForObject(getAccessTokenUrl, String.class);
 
        /**
         * 返回结果
         * {"access_token":"ACCESS_TOKEN","expires_in":7200}
         */
        if (!jsonStr.contains("access_token")) {
            System.out.println("获取access_token失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
 
        String accessTokenKey = WechatConfigure.BAIDU_ACCESS_TOKEN_REDIS_KEY;
        if (StrUtil.isEmpty(accessToken)) {
            log.error("获取baidu access_token失败: {}" , jsonObject.getString("errmsg"));
            throw new ApiException("获取access token失败");
        } else {
            log.info("baidu access_token : {}",accessToken);
            System.out.println(accessToken);
            redisUtils.set(accessTokenKey,accessToken);
        }
    }
 
}