应用jfinal发送微信模板消息的一个bug

严格来讲,这不是一个bug,只是我们应用的方式不对。微信发送模板消息的方法是:

HttpUtils.post(sendApiUrl + AccessTokenApi.getAccessTokenStr(), jsonStr);

在用这个方法时,多次调用的时候会出现无法收到消息的情况(尤其是停用好久没有调用的时候)。查日志返回值是40001,鉴权失败。

微信官方文档有说这个tokenl默认生成时间是7200秒也就是两个小时,在这两个小时能确保不过期你得自己做个定时器提交去刷新获取就成了。
这个问题,你应该是在本地access_token失效前提前去多远程服务器上获取access_token,这样就能确保你服务器的这个access_token是永久的生效,不然失效后你才去拿会造成访问access_token无效,访问中断的。

一种方法是再次调用,一种方法是启一个线程,定时更新。

再次调用的核心代码如下:

    private ApiResult sendSync(final String jsonStr) {
        final ApiResult result = TemplateMsgApi.send(jsonStr);
        LogKit.debug("**********发送模板消息**********");
        LogKit.debug(jsonStr);
        LogKit.debug("**********发送模板消息微信返回结果**********");
        LogKit.debug(result.getJson());
        return result;
    }

    /**
     * 异步发送
     */
    private void sendAsync(final String jsonStr) {
        if (this.executor == null) {
            this.executor = new ThreadPoolExecutor(5, 8, 200, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>());
        }
        Future<ApiResult> future = this.executor.submit(new Callable<ApiResult>() {
            @Override
            public ApiResult call() {
                LogKit.debug("模板消息异步发送...");
                return sendSync(jsonStr);
            }
        });
        try {
            logger.info("send wechat msg result = " + future.get().getJson());
            if (future.get().getErrorCode() != 0) {
                logger.warn("send wechat msg failed, resend");
                this.sendAsync(jsonStr);
            }
        } catch (InterruptedException | ExecutionException e) {
            logger.error("", e);
        }
    }

转载于:https://www.cnblogs.com/wardensky/p/8295380.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值