应用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);
		}
	}
posted @ 2018-01-16 10:46  wardensky  阅读(1016)  评论(0编辑  收藏  举报