暖冬已至,
圣诞老人就要背着大包裹降临剩单节了!
人美心善的艳艳也带来了剩单专属福利教程–Springboot+微信开发,
尽情享受这一波礼物风暴吧~
1、springboot+springmvc+mybatis开发的。
2、热加载 spring-boot-devtools
3、修改Spring加载图:resources目录下添加banner.txt,内容是在http://patorjk.com/software/taag/#p=testall&f=Graffiti&t=yanhui上制作
4、404和500
ModelAndView m = new ModelAndView();
m.addObject("yhExceptionClass", exception.getClass());
m.addObject("yhExceptionMsg", exception.getMessage());
StringBuffer url = request.getRequestURL();
String queryString = request.getQueryString();
String yhExceptionUrl = "";
if(queryString == null){
yhExceptionUrl = url+"";
}else {
yhExceptionUrl = url+"?"+queryString;
}
m.addObject("yhExceptionUrl", yhExceptionUrl);
ByteArrayOutputStream ostr = new ByteArrayOutputStream();
exception.printStackTrace(new PrintStream(ostr));
m.addObject("yhExceptionPrint", ostr+"");
m.setViewName("error/500");
5、日志配置
logging.path=F:\\demo
logging.file=demo.log
logging.level.root=info
这里需要注意几点:
这里若不配置具体的包的日志级别,日志文件信息将为空
若只配置logging.path,那么将会在F:\demo文件夹生成一个日志文件为spring.log
若只配置logging.file,那将会在项目的当前路径下生成一个demo.log日志文件
logging.path和logging.file同时配置,不会有在这个路径有F:\demo\demo.log日志生成,logging.path和logging.file不会进行叠加
logging.path和logging.file的value都可以是相对路径或者绝对路径
微信开发
一、Spring Boot中微信全局token的缓存实现
1.项目启动时开启一个定时器,每7180s执行一次Http请求,从微信获取最新的access_token并将redis中旧的access_token替换掉。
2. 代码中有需要使用access_token时,直接从缓存中读取。
实现:
定时器:app主方法添加 @EnableScheduling
创建一个定时类
package com.yanhui.weixin.timer;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.yanhui.weixin.redis.RedisTokenHelper;
import com.yanhui.weixin.util._wxPropertiesUtil;
import net.sf.json.JSONObject;
/**
* 全局定时器
*
*/
@Component
public class TokenTimer {
private static final Logger logger = LoggerFactory.getLogger(TokenTimer.class);
@Resource
private RedisTokenHelper redisTokenHelper;
/* @Scheduled(fixedRate=20000)
public void testTasks() {
logger.info("每20秒执行一次。开始……");
//statusTask.healthCheck();
logger.info("每20秒执行一次。结束。");
}
*/
/**
* 定时获取access_token
* @throws SQLException
*/
@Scheduled(fixedDelay=7180000)
public void getAccessToken() throws SQLException{
logger.info("==============开始获取access_token===============");
String access_token = null;
String grant_type = "client_credential";
String AppId= _wxPropertiesUtil.getProperty("appid");
String secret= _wxPropertiesUtil.getProperty("secret");
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+AppId+"&secret="+secret;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demoJson = JSONObject.fromObject(message);
//System.out.println("JSON字符串:"+demoJson);
access_token = demoJson.getString("access_token");
is.close();
logger.info("==============结束获取access_token===============");
} catch (Exception e) {
e.printStackTrace();
}
logger.info("==============开始写入access_token===============");
redisTokenHelper.saveObject("global_token", access_token);
logger.info("==============写入access_token成功===============");
}
}
2、单元测试test
package com.yanhui.weixin.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.yanhui.App;
import com.yanhui.weixin.redis.RedisTokenHelper;
/**
* Junit单元测试类
*
*/
@SuppressWarnings("deprecation")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes=App.class)
@WebAppConfiguration
public class JUnitTest {
private static final Logger logger = LoggerFactory.getLogger(JUnitTest.class);
@Autowired
private RedisTokenHelper redisTokenHelper;
@Test
public void test(){
String access_token = (String) redisTokenHelper.getObject("global_token");
System.out.println("access_token:"+access_token);
}
}
二、接入微信公众号,对消息的接收与回复
1、创建message包(req与resp)。
2、在util包中建立一个MessageUtil类来解析和响应消息。
3、在CoreServiceImpl.java中完善processRequest的逻辑。这里下章讲解。。。
需要所有源代码,可加QQ490647751回复‘一起艳学Springboot开发微信公众号(一)’获取。