SpringTask定时任务实例讲解【Java获取微信公众平台accessToken及jsapiTicket】

项目中调用微信公众平台的接口时,因为获取到的accessToken及jsapiTicket有效时长只有两个小时,需要不断更新。

所以做了个定时任务,记录一下。

.SpringTask实现有两种方式,一种是注解,一种是配置。我这个是配置xml实现的,实现步骤具体如下:

第一步:新建spring-task.xml,并配置定时任务。(先获取accessToken,在随即获取jsapiTicket)

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
         http://www.springframework.org/schema/task
         http://www.springframework.org/schema/task/spring-task-4.2.xsd">

<!-- 自动扫描的包名 -->
<context:component-scan base-package="com.wfcm.wxUitls" />
<task:annotation-driven /><!-- 定时器开关-->

<bean id="taskJob" class="com.wfcm.wxUitls.TaskJob"/><!-- 指向定时执行的类-->
<task:scheduled-tasks>
    <task:scheduled ref="taskJob" method="getAccessToken" cron="0 0 0/1 * * ?"/><!--每小时执行一次: ref指任务类bean的id , method定时执行的方法,corn定时设置-->
</task:scheduled-tasks>
<task:scheduled-tasks>
    <task:scheduled ref="taskJob" method="getJsapiTicket" cron="1 0 0/1 * * ?"/>
</task:scheduled-tasks>
</beans>
复制代码

记得扫描.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:spring-task.xml
    </param-value>
</context-param>

cron="0/2 * * * * ? //每两秒执行一次,测试的时候用。关于Spring Task 的 cron表达式,请参见另一篇博客:摆脱Spring 定时任务的@Scheduled cron表达式的困扰

 

 

第二步:接下来就是写任务类:(测试用)

复制代码
public class TaskJob {
    
    public void job1() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date now = new Date();
        System.out.println("******************任务进行中****************"+sdf.format(now));
    }
    
    public void job2() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date now = new Date();
        System.out.println("******************任务进行中****************"+sdf.format(now));
    }
}
复制代码

 

第三步:具体业务实现,其中access和jsapiticket存在同一张表中。

复制代码
package com.xxxx.wxUitls;public class TaskJob {

    private static Logger log = LoggerFactory.getLogger(TokenThread.class);  
    
    @Autowired
    WfWxShareService wxShareService;
    
    // 第三方用户唯一凭证  
    //appid/appsecret为微信app ; 配置获取access_token所需参数appid和appsecret
    public static String appid = "wxbxxxxxxxxxx";  
    // 第三方用户唯一凭证密钥  
    public static String appsecret = "4cfaxxxxxxxxxxxxxxxxx";  
   
    
    public void getAccessToken() {
        WfWxShareEntity accessToken = new WfWxShareEntity();  
        accessToken = WxUtil.getAccessToken(appid, appsecret); 
        if (null != accessToken ) {  
            log.info("获取access_token成功,有效时长{}秒 token:{}", accessToken.getContent());
            wxShareService.update(accessToken);
        }
    }
    
    public void getJsapiTicket() {
        WfWxShareEntity accessToken = new WfWxShareEntity();  
        accessToken = wxShareService.queryObject(1);
        
        JSONObject jsonObj= FastJSONUtils.getJSONObject(accessToken.getContent());  
        String access_token = jsonObj.getString("access_token");
        
        WfWxShareEntity jsapiTicket = new WfWxShareEntity();
        jsapiTicket = WxUtil.getTicket(access_token);
        if (null != jsapiTicket ) {  
            log.info("获取jsapiTicket成功,有效时长{}秒 token:{}", jsapiTicket.getContent());
        }
        wxShareService.update(jsapiTicket);
    }
    
}
复制代码

 

工具类:WXUtil.java

复制代码
package com.xxxx.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import com.xxxx.entity.WfWxShareEntity;

public class WxUtil {

    /**
     * 向指定URL发送GET方法的请求
     * 
     *            发送请求的URL
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static WfWxShareEntity getAccessToken(String appid, String appsecret) {
        WfWxShareEntity accessToken = new WfWxShareEntity(); 
        
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" +appid+ "&secret=" + appsecret;
            
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
           String line =null;
            while ((line = in.readLine()) != null) {
                result += line;
            }
           // JSONObject jsonObj= FastJSONUtils.getJSONObject(result);  
            /* String access_token = jsonObj.getString("access_token");
            long expires_in = Long.valueOf(jsonObj.getString("expires_in"));*/
            accessToken.setId(1);
            accessToken.setName("access_token");
            accessToken.setContent(result);
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return  accessToken ;
    }    
        
    /**
     * 向指定URL发送GET方法的请求
     *            发送请求的URL
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static WfWxShareEntity getTicket(String access_token) {
        WfWxShareEntity jsapiTicket = new WfWxShareEntity(); 
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = " https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" +access_token+ "&type=jsapi";
            
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
           String line =null;
            while ((line = in.readLine()) != null) {
                result += line;
            }
/*            JSONObject jsonObj= FastJSONUtils.getJSONObject(result);  
            String tiket = jsonObj.getString("ticket");
            long expires_in = Long.valueOf(jsonObj.getString("expires_in"));
            accessToken.setAccessToken(tiket);
            accessToken.setExpirationTime(expires_in);*/
            jsapiTicket.setId(2);
            jsapiTicket.setName("jsapi_ticket");
            jsapiTicket.setContent(result);
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return  jsapiTicket ;
    }    
        
}
复制代码

 

实体类:WxSharEntity.java

复制代码
package com.xxx.entity;

import java.io.Serializable;
import java.util.Date;



/**
 * 微信分享
 * 
 * @author xlf
 * @email xlfbe696@gmail.com
 * @date 2018-02-01 19:44:58
 */
public class WfWxShareEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    
    //
    private Integer id;
    //名称
    private String name;
    //内容
    private String content;

    /**
     * 设置:
     */
    public void setId(Integer id) {
        this.id = id;
    }
    /**
     * 获取:
     */
    public Integer getId() {
        return id;
    }
    /**
     * 设置:名称
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * 获取:名称
     */
    public String getName() {
        return name;
    }
    /**
     * 设置:内容
     */
    public void setContent(String content) {
        this.content = content;
    }
    /**
     * 获取:内容
     */
    public String getContent() {
        return content;
    }
}
复制代码

 

posted @ 2020-05-07 15:06  YoungDeng  阅读(580)  评论(0编辑  收藏  举报