• 应用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);
    		}
    	}
    
  • 相关阅读:
    Sencha, the nightmare!
    最近这一年
    SharePoint 是哪些人设计、开发的?
    用 Excel 测试“绘制两点间连线”的算法
    实现一个基于 SharePoint 2013 的 Timecard 应用(下)
    实现一个基于 SharePoint 2013 的 Timecard 应用(中)
    实现一个基于 SharePoint 2013 的 Timecard 应用(上)
    ASP.NET 在 Windows Azure 环境中使用基于 SQLServer 的 Session
    SQLServer 查询使用键查找时锁申请及释放顺序
    由delete导致的超时已过期问题
  • 原文地址:https://www.cnblogs.com/wardensky/p/8295380.html
Copyright © 2020-2023  润新知