有人说程序员不懂浪漫,其实他们都误会了。今天给大家分享一个小技巧。使用SpringBoot通过微信每天给心爱的姑娘发浪漫的话不一定要赢~
准备工作
申请微信开放平台测试号
申请微信测试公众号:T=sandbox/index
成功创建后,可以查看appid和appsecret
请购单样版
今天是:{{now。DATA}}不管是那一天,每天都在想念你
当前城市:{{ci}}
今天的天气:{{}}
最低气温:{{low。DATA}}度
最高气温:{{}}度
今天是我们想爱的第一天:{{}}天
直到你生日:{{bir_day。DATA}}天
{{daily_engli}}
{{daily_engli}}请记住,创建新模板后保存模板Id在以后很有用
扫描正在关注这个测试公众号
码关注后,记录微信号,后续推送通知
百度天气申请
百度天气API申请:
认证完成后,请创建应用程序并保存AK
天行数据申请接口
申请天行数据:
阿兰放屁申请每天完成一句申请后,记住存储申请界面的键
开发工作
技术堆栈说明
spring boot 2 . 7 . 5 swagger 3 . 0 MySQL 8 . x spring data jpaopenfeign从属组件
?嗯?Xml版本=' 1.0' encoding=' utf-8 '
项目xmlns='xmlns : xsi='
xsi : schemalocation='
ModelVersion4.0.0/modelVersion
GroupIdcom.zhao/groupId
artifactiddaily-weather/artifact id
版本1.0.0/版本
l
t;name>daily-weather</name> <description>微信用户推送消息</description> <properties> <java.version>1.8<; <;UTF-8</; <;UTF-8</; <;2.7.5</; <;3.0.0</; <kni;3.0.3</kni; <;2.0.15<; <o;3.1.3</o; <;5.7.5</; </properties> <dependencies> <!--hutools--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-core</artifactId> <version>${}</version> </dependency> <!--fastjson--> <dependency> <groupId>com.alibaba.fastjson2</groupId> <artifactId>fastjson2</artifactId> <version>${}</version> </dependency> <!--open feign--> <dependency> <groupId>org.;/groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>${o}</version> </dependency> <!--weixin-java-mp--> <dependency> <groupId>com.gi;/groupId> <artifactId>weixin-java-mp</artifactId> <version>3.3.0</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>${}</version> </dependency> <!--换掉默认皮肤--> <dependency> <groupId>com.gi;/groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>${kni}</version> </dependency> <dependency> <groupId>org.;/groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.;/groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.;/groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.;/groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> </project>配置文件
Server:
port: 43310
# 微信配置
tencent:
wechat:
appId: 微信appid
appSecret: 微信appSecret
# 模板消息集合
templatelist:
- type: 1
templateId: 微信模板id
- type: 2
templateId: 微信模板id
- type: 3
templateId: 微信模板id
# 百度天气配置
baidu:
server:
ak: 百度数据的ak
# 天行数据
tianxin:
server:
key: 天行数据的key
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
datasource:
type: com.zaxxer.
driver-class-name: com.my
url: jdbc:mysql://ip:3306/库名?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: 564929
hikari:
minimum-idle: 5
# 空闲连接存活最大时间,默认600000(10分钟)
idle-timeout: 180000
# 连接池最大连接数,默认是10
maximum-pool-size: 10
# 此属性控制从池返回的连接的默认自动提交行为,默认值:true
auto-commit: true
# 连接池名称
pool-name: MyHikariCP
# 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
max-lifetime: 1800000
# 数据库连接超时时间,默认30秒,即30000
connection-timeout: 30000
connection-test-query: SELECT 1
jpa:
show-sql: true # 默认false,在日志里显示执行的sql语句
database: mysql
database-platform: org.
hibernate:
ddl-auto: update #指定为update,每次启动项目检测表结构有变化的时候会新增字段,表不存在时会 新建,如果指定create,则每次启动项目都会清空数据并删除表,再新建
naming:
#指定jpa的自动表生成策略,驼峰自动映射为下划线格式7
implicit-strategy: org.
#physical-strategy: org.
统一数据封装
package com.z;
/**
* 对前端响应结果统一封装
*/
@Slf4j
@RestControllerAdvice(basePackages = {"com.z;})
public class ApiResponseAdvice implements ResponseBodyAdvice<Object> {
/**
* 打印统一请求响应规范
*/
ApiResponseAdvice(){
log.info("启动请求统一响应规范... ...");
}
/**
* 判断是否需要对返回值进行封装
* @param returnType the return type
* @param converterType the selected converter type
* @return
*/
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
// 如果返回的结果是Re类型就不用封装
if ().equals(Re)){
return false;
}
return true;
}
/**
* 对返回前端的值统一封装
* @param body the body to be written
* @param returnType the return type of the controller method
* @param selectedContentType the content type selected through content negotiation
* @param selectedConverterType the converter type selected to write to the response
* @param request the current request
* @param response the current response
* @return
*/
@Override
public Object beforeBodyWrite(Object body,
MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request,
ServerHttpResponse response) {
if ().equal)){
// 如果是String类需要特殊处理
ObjectMapper objectMapper = new ObjectMapper();
try {
// 设置响应数据格式为json
re().add("content-type","application/json;charset=UTF-8");
return objec(body));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
return Re(body);
}
工程结构
用户controller
package com.z;
import java.u;
/**
* 用户信息管理视图层
*/
@RestController
@RequestMapping("/userInfo")
@Api(tags = "用户信息管理")
public class UserInfoRest {
@Autowired
private UserInfoService userInfoService;
/**
* 分页获取所有的用户
* @return
*/
@ApiOperation(value = "分页获取所有的用户")
@PostMapping("/queryPage")
public Page<UserInfo> queryUserPage(@PageableDefault Pageable pageable){
Page<UserInfo> userInfos = u(), ());
return userInfos;
}
/**
* 添加或者修改用户
*/
@ApiOperation(value = "添加或者修改用户")
@PostMapping("/saveOrUpdate")
public void saveOrUpdate(@RequestBody UserInfo userInfo){
u(userInfo);
}
/**
* 删除用户
*/
@ApiOperation(value = "删除用户")
@DeleteMapping("/delete")
public void deleteUserById(@RequestParam("id") Long id){
u(id);
}
}
调用第三方接口
package com.z;
/**
* 第三方接口天行数据
*/
@FeignClient(value = "TianDataRemoteClient",url = "${}")
public interface TianDataRemoteClient {
/**
* 获取彩虹屁
*/
@GetMapping(value = "/caihongpi/index",
consumes = {MediaTy},
produces = {MediaTy}
)
String queryRainbow(@SpringQueryMap TianXinParam tianXinParam);
/**
* 获取优美的句子
*/
@GetMapping(value = "/ensentence/index",
consumes = {MediaTy},
produces = {MediaTy}
)
String queryEnsentence(@SpringQueryMap TianXinParam tianXinParam);
}
推送微信数据
package com.z;
@Slf4j
@Service
public class PushDailyWechatImpl implements PushDailyWechat{
@Autowired
private UserInfoService userInfoService;
@Autowired
private BaiduWeatherRemoteClient baiduWeatherRemoteClient;
@Autowired
private TianDataRemoteClient tianDataRemoteClient;
/** 微信配置类 **/
@Autowired
private WechatConfig wechatConfig;
/** 模板列表**/
@Autowired
private WechatTemplateList wechatTemplateList;
/** ak **/
@Value("${baidu.ak}")
private String ak;
/** key **/
@Value("${}")
private String key;
/**
* 给不同的用户推送消息
*/
@Override
public void pushWechat() throws WxErrorException {
// 获取用户列表
List<UserInfo> userInfoList = u();
if (!Collec(userInfoList)){
// 根据用户的type类型和模板type进行匹配
for (UserInfo userInfo : userInfoList) {
for (WechatTemplate template : wec()) {
if ().equal())){
(), (),userInfo);
}
}
}
}
}
/**
* 封装微信数据
* @param wechatId
* @param templateId
*/
private void wechatData(String wechatId,String templateId,UserInfo userInfo) throws WxErrorException {
// 创建配置信息
WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
wxS());
wxS());
WxMpService wxMpService = new WxMpServiceImpl();
wxM(wxStorage);
// 创建模板信息
WxMpTemplateMessage templateMessage = WxM()
.toUser(wechatId)
.templateId(templateId)
.build();
// 获取天气预报信息
BaiduWeatherParam baiduWeatherParam = BaiduWea()
.district_id())
.data_type("all")
.ak)
.build();
String queryWeather = baiduWea(baiduWeatherParam);
log.info("查询的百度天气信息为:{}",queryWeather);
BaiduNowWeather baiduNowWeather = A(queryWeather, BaiduNowWea);
List<BaiduForecastsWeather> baiduForecastsWeatherList = A(queryWeather, BaiduForecastsWea);
log.info("baiduNowWeather:{},baiduForecastsWeather:{}",baiduNowWeather,baiduForecastsWeatherList);
// 获取彩虹屁
TianXinParam tianXinParam = TianXinParam.builder().key).build();
String queryRainbow = (tianXinParam);
List<TianRainbow> rainbowList = A(queryRainbow, TianRainbow.class);
// 获取每日一句
String queryEnsentence = (tianXinParam);
List<TianEnsentence> tianEnsentenceList = A(queryEnsentence, TianEn);
// 封装模板数据
(new WxMpTemplateData("now", (0)),"#FFB6C1"));
(new WxMpTemplateData("city",u(),"#B95EA6"));
(new WxMpTemplateData("text",baiduNowWea(),"#173177"));
(new WxMpTemplateData("high",baiduForeca(0).getHigh(),"#87cefa"));
(new WxMpTemplateData("low",baiduForeca(0).getLow(),"#FF6347"));
(new WxMpTemplateData("scq_day",(userInfo),"#FF1493"));
(new WxMpTemplateData("bir_day",(userInfo),"#FF00FF" ));
(new WxMpTemplateData("daily_english_cn",rainbowLi(0).getContent(),"#800080"));
(new WxMpTemplateData("daily_english_en",tianEnsentenceLi(0).getEn(),"#FFA500"));
log.info("发送的消息为:{}", JSON.toJSONString(templateMessage));
wxM().sendTemplateMsg(templateMessage);
}
/**
* 计算想认识/想恋日期
* @return
*/
private String calScqDate(UserInfo userInfo){
// 获取第一次想认识的时间
if (userInfo)){
Date scqTime = u();
// 计算时间差
long between = Da(scqTime, Da(), Da);
return S(between);
}
return "";
}
/**
* 计算生日
* @param userInfo
* @return
*/
private String calBirData(UserInfo userInfo){
// 获取用户的出生日期
if (userInfo)){
Date birTime = u();
// 今日日期
Calendar today = Calendar.getInstance();
// 出生日期
Calendar birthDay = Calendar.getInstance();
// 设置生日
bir(birTime);
// 修改为本年
int bir;
bir));
if ) < )){
// 生日已经过了,计算明年的
bir = ActualMaximum) - );
bir += bir);
} else {
// 生日还没过
bir = bir) - );
}
return S(bir);
}
return "";
}
/**
* 拼接今日时间
* @return
*/
private String pareDateNow(BaiduForecastsWeather baiduForecastsWeather){
// 获取当前日期
String now = Da(Da(), Da);
// 获取星期几
String week = baiduForeca();
return now+" "+week;
}
}
定时任务
package com.z;
/**
* 推送消息到用户定时任务
*/
@Component
public class PushWechatJob {
@Autowired
private PushDailyWechat pushDailyWechat;
/**
* 每天早上7点推送到微信
* @throws WxErrorException
*/
@Scheduled(cron = "0 30 7 1/1 * ? ")
void doJob() throws WxErrorException {
();
}
}
效果
推送到微信