3 Commits

Author SHA1 Message Date
bamanker
1c133b59f6 用webclient重构
All checks were successful
Build Push and Deploy Image / build (push) Successful in 25m25s
2026-01-13 15:54:21 +08:00
bamanker
e33eea291c 用webclient重构 2026-01-13 15:53:46 +08:00
bamanker
6f9816a695 变更为webclient响应式客户端 2026-01-12 18:07:12 +08:00
16 changed files with 559 additions and 204 deletions

21
pom.xml
View File

@@ -33,7 +33,7 @@
<maven.compiler.source>25</maven.compiler.source>
<maven.compiler.target>25</maven.compiler.target>
<!-- <fastjson.version>2.0.60</fastjson.version>-->
<openfeign.version>5.0.0</openfeign.version>
<!-- <openfeign.version>5.0.0</openfeign.version>-->
<hutool.version>5.8.25</hutool.version>
<docker.private.repository>registry.cn-chengdu.aliyuncs.com/bamanker</docker.private.repository>
<!-- <docker.private.repository>172.17.0.1:10888/my_work</docker.private.repository>-->
@@ -55,11 +55,11 @@
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>${openfeign.version}</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-openfeign</artifactId>-->
<!-- <version>${openfeign.version}</version>-->
<!-- </dependency>-->
<!-- 如果需要显式指定 Jackson 3 -->
<dependency>
<groupId>tools.jackson.core</groupId>
@@ -92,6 +92,15 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>dailylove</finalName>

View File

@@ -1,17 +1,14 @@
package com.bamanker.dailylove;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author bamanker
*/
@SpringBootApplication
@EnableFeignClients
//@EnableFeignClients
//开启定时任务
@EnableScheduling
//@ImportAutoConfiguration({FeignAutoConfiguration.class})

View File

@@ -1,7 +1,6 @@
package com.bamanker.dailylove.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**

View File

@@ -1,15 +0,0 @@
package com.bamanker.dailylove.config;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignConfig
{
@Bean
Logger.Level feignLoggerLevel()
{
return Logger.Level.FULL;
}
}

View File

@@ -1,11 +1,9 @@
package com.bamanker.dailylove.config;
import com.bamanker.dailylove.controller.PushDailyController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
//@Component
public class PushTask {
final

View File

@@ -0,0 +1,57 @@
package com.bamanker.dailylove.config;
import io.netty.handler.logging.LogLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.transport.logging.AdvancedByteBufFormat;
/**
* @author bamanker
* @descriptions webclent 配置类
* @date 2026/1/12 17:33
* @return
*/
@Configuration
@Slf4j
public class WebClientConfig {
HttpClient httpClient = HttpClient.create().wiretap("reactor.netty.http.client.HttpClient",
LogLevel.DEBUG,
AdvancedByteBufFormat.TEXTUAL);
/**
* 创建WebClient Bean
*/
@Bean
public WebClient wechatWebClient() {
return WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient))
.filter((request, next) -> {
log.info("wechatRequest: {}", request.url());
return next.exchange(request);
})
.baseUrl("https://api.weixin.qq.com/cgi-bin") // 基础URL
.defaultHeader("User-Agent", "WebFlux-Client") // 默认请求头
.build();
}
@Bean
public WebClient dateRemoteClient() {
return WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient))
.filter((request, next) -> {
log.info("tianxingRequest: {}", request.url());
return next.exchange(request);
})
.baseUrl("https://apis.tianapi.com")
.defaultHeader("User-Agent", "WebFlux-Client")
.build();
}
}

View File

@@ -4,19 +4,22 @@ import cn.hutool.core.date.ChineseDate;
import cn.hutool.core.date.DateUtil;
import com.bamanker.dailylove.config.DailyLoveConfigure;
import com.bamanker.dailylove.domain.*;
import com.bamanker.dailylove.service.DataRemoteClient;
import com.bamanker.dailylove.service.WechatRequestClient;
import com.bamanker.dailylove.service.DataRemoteService;
import com.bamanker.dailylove.service.WechatRequestService;
import com.bamanker.dailylove.utils.DataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aot.hint.annotation.RegisterReflectionForBinding;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple5;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.function.Function;
/**
* @author bamanker
@@ -29,20 +32,21 @@ import java.util.Date;
public class PushDailyController {
final
ObjectMapper mapper;
JsonMapper mapper;
final
DataRemoteClient dataRemoteClient;
DataRemoteService dataRemoteService;
final
WechatRequestClient wechatRequestClient;
WechatRequestService wechatRequestService;
public PushDailyController(DataRemoteClient dataRemoteClient, WechatRequestClient wechatRequestClient, ObjectMapper mapper) {
this.dataRemoteClient = dataRemoteClient;
this.wechatRequestClient = wechatRequestClient;
public PushDailyController(JsonMapper mapper, DataRemoteService dataRemoteService, WechatRequestService wechatRequestService) {
this.mapper = mapper;
this.dataRemoteService = dataRemoteService;
this.wechatRequestService = wechatRequestService;
}
/**
* 推送晚安
*
@@ -50,7 +54,7 @@ public class PushDailyController {
*/
@GetMapping("/pushNight")
@RegisterReflectionForBinding(Weather.class)
public String pushNight() {
public Mono<String> pushNight() {
ResultVo resultVo = ResultVo.initializeResultVo(DailyLoveConfigure.Open_ID,
DailyLoveConfigure.Template_ID_Night,
@@ -60,40 +64,70 @@ public class PushDailyController {
param1.setKey(DailyLoveConfigure.TianXin_Key);
param1.setCity(DailyLoveConfigure.City_ID);
param1.setType("7");
String weatherResp = dataRemoteClient.getWeather(param1);
JsonNode weatherJson = mapper.readTree(weatherResp).get("result").get("list").get(1);
String city = mapper.readTree(weatherResp).get("result").get("area").asString();
Weather weather = mapper.treeToValue(weatherJson, Weather.class);
resultVo.setAttribute("tomorrow", new DataItem(weather.getDate() + " " + weather.getWeek(), DailyLoveConfigure.Color_tomorrow));
resultVo.setAttribute("city", new DataItem(city, DailyLoveConfigure.Color_city));
resultVo.setAttribute("weather", new DataItem(weather.getWeather(), DailyLoveConfigure.Color_weather));
resultVo.setAttribute("min_temperature", new DataItem(weather.getLowest(), DailyLoveConfigure.Color_minTem));
resultVo.setAttribute("max_temperature", new DataItem(weather.getHighest(), DailyLoveConfigure.Color_maxTem));
resultVo.setAttribute("quality", new DataItem(weather.getVis(), DailyLoveConfigure.Color_quality));
Mono<String> weatherRespMono = dataRemoteService.getWeather(param1.getKey(), param1.getCity(), param1.getType());
Mono<ResultVo> resultVoMono1 = weatherRespMono
.map(respJson -> mapper.readTree(respJson)
.get("result")
.get("area")
.toString())
.flatMap(city -> {
resultVo.setAttribute("city", new DataItem(city, DailyLoveConfigure.Color_city));
return Mono.just(resultVo);
});
Mono<ResultVo> resultVoMono2 = weatherRespMono
.map(respJson -> mapper.readTree(respJson)
.get("result")
.get("list")
.get(1))
.map(respJson -> mapper.treeToValue(respJson, Weather.class))
.flatMap(weather -> {
resultVo.setAttribute("tomorrow", new DataItem(weather.getDate() + " " + weather.getWeek(), DailyLoveConfigure.Color_tomorrow));
resultVo.setAttribute("weather", new DataItem(weather.getWeather(), DailyLoveConfigure.Color_weather));
resultVo.setAttribute("min_temperature", new DataItem(weather.getLowest(), DailyLoveConfigure.Color_minTem));
resultVo.setAttribute("max_temperature", new DataItem(weather.getHighest(), DailyLoveConfigure.Color_maxTem));
resultVo.setAttribute("quality", new DataItem(weather.getVis(), DailyLoveConfigure.Color_quality));
return Mono.just(resultVo);
});
// Mono<Tuple2<ResultVo, ResultVo>> zip = Mono.zip(resultVoMono1, resultVoMono);
TianXinReqParam param2 = new TianXinReqParam();
param2.setKey(DailyLoveConfigure.TianXin_Key);
String tipsResp = dataRemoteClient.getTips(param2);
String tips = mapper.readTree(tipsResp).get("result").get("content").asString();
resultVo.setAttribute("tips", new DataItem(tips, DailyLoveConfigure.Color_tips));
Mono<ResultVo> resultVoMono3 = dataRemoteService.getTips(param2.getKey(), param2.getCity(), param2.getType())
.map(respJson -> mapper.readTree(respJson)
.get("result")
.get("content").asString())
.flatMap(tips -> {
resultVo.setAttribute("tips", new DataItem(tips, DailyLoveConfigure.Color_tips));
return Mono.just(resultVo);
});
Mono<ResultVo> resultVoMono4 = dataRemoteService.getNight(param2.getKey(), param2.getCity(), param2.getType())
.map(respJson -> mapper.readTree(respJson)
.get("result")
.get("content").asString())
.flatMap(night -> {
resultVo.setAttribute("night", new DataItem(night, DailyLoveConfigure.Color_night));
return Mono.just(resultVo);
});
Mono<ResultVo> resultVoMono5 = dataRemoteService.getRainbow(param2.getKey(), param2.getCity(), param2.getType())
.map(respJson -> mapper.readTree(respJson)
.get("result")
.get("content").asString())
.flatMap(rainbow -> {
resultVo.setAttribute("rainbow", new DataItem(rainbow, DailyLoveConfigure.Color_dailyCn));
return Mono.just(resultVo);
});
String nightResp = dataRemoteClient.getNight(param2);
String night = mapper.readTree(nightResp).get("result").get("content").asString();
resultVo.setAttribute("night", new DataItem(night, DailyLoveConfigure.Color_night));
Mono<ResultVo> resultVoMono = Mono.zip(resultVoMono1, resultVoMono2, resultVoMono3, resultVoMono4, resultVoMono5)
.flatMap(new Function<Tuple5<ResultVo, ResultVo, ResultVo, ResultVo, ResultVo>, Mono<? extends ResultVo>>() {
@Override
public Mono<? extends ResultVo> apply(Tuple5<ResultVo, ResultVo, ResultVo, ResultVo, ResultVo> tuple) {
return Mono.just(tuple.getT1());
}
});
String rainbowResp = dataRemoteClient.getRainbow(param2);
String rainbow = mapper.readTree(rainbowResp).get("result").get("content").asString();
resultVo.setAttribute("rainbow", new DataItem(rainbow, DailyLoveConfigure.Color_dailyCn));
// String englishResp = dataRemoteClient.getDailyEnglish(param2);
// String english = JSONObject.parseObject(englishResp).getJSONArray("result").getJSONObject(0).getString("en");
// resultVo.setAttribute("daily_english_en", new DataItem(english, DailyLoveConfigure.Color_dailyEn));
ChineseDate chineseDate = new ChineseDate(DateUtil.parseDate(weather.getDate()));
ChineseDate chineseDate = new ChineseDate(DateUtil.parseDate(LocalDate.now().toString()));
String festival = chineseDate.getFestivals();
String term = chineseDate.getTerm();
resultVo.setAttribute("lunar", new DataItem(chineseDate.toString(), DailyLoveConfigure.Color_chineseDate));
@@ -138,16 +172,23 @@ public class PushDailyController {
log.info("wedding_days:{}", weddingDays);
resultVo.setAttribute("wedding_day", new DataItem(weddingDays + 1 + "", DailyLoveConfigure.Color_weddingDay));
log.info("resultVo:{}", resultVo);
WechatTokenParam wechatTokenParam = new WechatTokenParam();
wechatTokenParam.setAppid(DailyLoveConfigure.App_ID);
wechatTokenParam.setSecret(DailyLoveConfigure.App_Secret);
resultVoMono.flatMap(new Function<ResultVo, Mono<?>>() {
@Override
public Mono<?> apply(ResultVo resultVo) {
return Mono.just(resultVo);
}
}).log().block();
String accessTokenResp = wechatRequestClient.getAccessToken(wechatTokenParam);
log.info("accessTokenJson:{}", accessTokenResp);
String token = mapper.readTree(accessTokenResp).get("access_token").asString();
// String token1 = JSONObject.parseObject(accessTokenResp).getString("access_token");
return wechatRequestClient.sendMsg(resultVo, token);
WechatTokenParam param3 = new WechatTokenParam();
param3.setAppid(DailyLoveConfigure.App_ID);
param3.setSecret(DailyLoveConfigure.App_Secret);
String accessToken = wechatRequestService.getAccessToken(param3.getGrant_type(), param3.getAppid(), param3.getSecret())
.map(respJson -> {
return mapper.readTree(respJson)
.get("access_token").asString();
}).log().block();
return wechatRequestService.sendMsg(accessToken, resultVo).log();
}
@@ -156,55 +197,85 @@ public class PushDailyController {
*/
@GetMapping("/pushMorning")
@RegisterReflectionForBinding(Weather.class)
public String pushMorning() {
TianXinReqParam param1 = new TianXinReqParam();
param1.setKey(DailyLoveConfigure.TianXin_Key);
param1.setCity(DailyLoveConfigure.City_ID);
param1.setType("1");
String weatherResp = dataRemoteClient.getWeather(param1);
JsonNode weatherJson = mapper.readTree(weatherResp).get("result");
Weather weather = mapper.treeToValue(weatherJson, Weather.class);
// Weather weather1 = JSONObject.parseObject(weatherResp).getJSONArray("result").getJSONObject(0).toJavaObject(Weather.class);
public Mono<String> pushMorning() {
ResultVo resultVo = ResultVo.initializeResultVo(DailyLoveConfigure.Open_ID,
DailyLoveConfigure.Template_ID_Morning,
DailyLoveConfigure.Color_Top);
resultVo.setAttribute("now", new DataItem(weather.getDate() + " " + weather.getWeek(), DailyLoveConfigure.Color_Now));
resultVo.setAttribute("city", new DataItem(weather.getArea(), DailyLoveConfigure.Color_city));
resultVo.setAttribute("weather", new DataItem(weather.getWeather(), DailyLoveConfigure.Color_weather));
resultVo.setAttribute("min_temperature", new DataItem(weather.getLowest(), DailyLoveConfigure.Color_minTem));
resultVo.setAttribute("max_temperature", new DataItem(weather.getHighest(), DailyLoveConfigure.Color_maxTem));
resultVo.setAttribute("quality", new DataItem(weather.getQuality(), DailyLoveConfigure.Color_quality));
TianXinReqParam param1 = new TianXinReqParam();
param1.setKey(DailyLoveConfigure.TianXin_Key);
param1.setCity(DailyLoveConfigure.City_ID);
param1.setType("7");
Mono<String> weatherRespMono = dataRemoteService.getWeather(param1.getKey(), param1.getCity(), param1.getType());
Mono<ResultVo> resultVoMono1 = weatherRespMono
.map(respJson -> mapper.readTree(respJson)
.get("result")
.get("area")
.toString())
.flatMap(city -> {
resultVo.setAttribute("city", new DataItem(city, DailyLoveConfigure.Color_city));
return Mono.just(resultVo);
});
Mono<ResultVo> resultVoMono2 = weatherRespMono
.map(respJson -> mapper.readTree(respJson)
.get("result")
.get("list")
.get(0))
.map(respJson -> mapper.treeToValue(respJson, Weather.class))
.flatMap(weather -> {
resultVo.setAttribute("now", new DataItem(weather.getDate() + " " + weather.getWeek(), DailyLoveConfigure.Color_Now));
resultVo.setAttribute("weather", new DataItem(weather.getWeather(), DailyLoveConfigure.Color_weather));
resultVo.setAttribute("min_temperature", new DataItem(weather.getLowest(), DailyLoveConfigure.Color_minTem));
resultVo.setAttribute("max_temperature", new DataItem(weather.getHighest(), DailyLoveConfigure.Color_maxTem));
resultVo.setAttribute("quality", new DataItem(weather.getVis(), DailyLoveConfigure.Color_quality));
return Mono.just(resultVo);
});
// Mono<Tuple2<ResultVo, ResultVo>> zip = Mono.zip(resultVoMono1, resultVoMono);
TianXinReqParam param2 = new TianXinReqParam();
param2.setKey(DailyLoveConfigure.TianXin_Key);
// String tipsResp = dataRemoteClient.getTips(param2);
// String tips = JSONObject.parseObject(tipsResp).getJSONArray("result").getJSONObject(0).getString("content");
// resultVo.setAttribute("tips", new DataItem(tips, DailyLoveConfigure.Color_tips));
Mono<ResultVo> resultVoMono3 = dataRemoteService.getTips(param2.getKey(), param2.getCity(), param2.getType())
.map(respJson -> mapper.readTree(respJson)
.get("result")
.get("content").asString())
.flatMap(tips -> {
resultVo.setAttribute("tips", new DataItem(tips, DailyLoveConfigure.Color_tips));
return Mono.just(resultVo);
});
Mono<ResultVo> resultVoMono4 = dataRemoteService.getMorning(param2.getKey(), param2.getCity(), param2.getType())
.map(respJson -> mapper.readTree(respJson)
.get("result")
.get("content").asString())
.flatMap(morning -> {
resultVo.setAttribute("morning", new DataItem(morning, DailyLoveConfigure.Color_morning));
return Mono.just(resultVo);
});
Mono<ResultVo> resultVoMono5 = dataRemoteService.getRainbow(param2.getKey(), param2.getCity(), param2.getType())
.map(respJson -> mapper.readTree(respJson)
.get("result")
.get("content").asString())
.flatMap(rainbow -> {
resultVo.setAttribute("rainbow", new DataItem(rainbow, DailyLoveConfigure.Color_dailyCn));
return Mono.just(resultVo);
});
String morningResp = dataRemoteClient.getMorning(param2);
String morning = mapper.readTree(morningResp).get("result").get("content").asString();
// String morning1 = JSONObject.parseObject(morningResp).getJSONArray("result").getJSONObject(0).getString("content");
resultVo.setAttribute("morning", new DataItem(morning, DailyLoveConfigure.Color_morning));
Mono<ResultVo> resultVoMono = Mono.zip(resultVoMono1, resultVoMono2, resultVoMono3, resultVoMono4, resultVoMono5)
.flatMap(new Function<Tuple5<ResultVo, ResultVo, ResultVo, ResultVo, ResultVo>, Mono<? extends ResultVo>>() {
@Override
public Mono<? extends ResultVo> apply(Tuple5<ResultVo, ResultVo, ResultVo, ResultVo, ResultVo> tuple) {
return Mono.just(tuple.getT1());
}
});
String rainbowResp = dataRemoteClient.getRainbow(param2);
String rainbow = mapper.readTree(rainbowResp).get("result").get("content").asString();
// String rainbow1 = JSONObject.parseObject(rainbowResp).getJSONArray("result").getJSONObject(0).getString("content");
resultVo.setAttribute("rainbow", new DataItem(rainbow, DailyLoveConfigure.Color_dailyCn));
// String englishResp = dataRemoteClient.getDailyEnglish(param2);
// String english = JSONObject.parseObject(englishResp).getJSONArray("result").getJSONObject(0).getString("en");
// resultVo.setAttribute("daily_english_en", new DataItem(english, DailyLoveConfigure.Color_dailyEn));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String currentTime = dateFormat.format(date);
ChineseDate chineseDate = new ChineseDate(DateUtil.parseDate(currentTime));
ChineseDate chineseDate = new ChineseDate(DateUtil.parseDate(LocalDate.now().toString()));
String festival = chineseDate.getFestivals();
String term = chineseDate.getTerm();
resultVo.setAttribute("lunar", new DataItem(chineseDate.toString(), DailyLoveConfigure.Color_chineseDate));
@@ -254,11 +325,18 @@ public class PushDailyController {
wechatTokenParam.setAppid(DailyLoveConfigure.App_ID);
wechatTokenParam.setSecret(DailyLoveConfigure.App_Secret);
String accessTokenResp = wechatRequestClient.getAccessToken(wechatTokenParam);
log.debug("accessTokenJson:{}", accessTokenResp);
String token = mapper.readTree(accessTokenResp).get("access_token").asString();
// String token1 = JSONObject.parseObject(accessTokenResp).getString("access_token");
return wechatRequestClient.sendMsg(resultVo, token);
resultVoMono.flatMap((Function<ResultVo, Mono<?>>) resultVo1 -> Mono.just(resultVo1)).log().block();
WechatTokenParam param3 = new WechatTokenParam();
param3.setAppid(DailyLoveConfigure.App_ID);
param3.setSecret(DailyLoveConfigure.App_Secret);
String accessToken = wechatRequestService.getAccessToken(param3.getGrant_type(), param3.getAppid(), param3.getSecret())
.map(respJson -> {
return mapper.readTree(respJson)
.get("access_token").asString();
}).log().block();
return wechatRequestService.sendMsg(accessToken, resultVo).log();
}
@@ -278,5 +356,4 @@ public class PushDailyController {
System.out.println("[ " + dateFormat.format(new Date()) + " ] : messageCode=" + msgCode + ",messageContent=" + msgContent);
}
}

View File

@@ -0,0 +1,10 @@
package com.bamanker.dailylove.domain;
import lombok.Data;
@Data
public class ErrorResponse {
private Integer code;
private String message;
}

View File

@@ -0,0 +1,34 @@
package com.bamanker.dailylove.exception;
import com.bamanker.dailylove.domain.ErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import reactor.core.publisher.Mono;
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理运行时异常
*/
@ExceptionHandler(RuntimeException.class)
public Mono<ResponseEntity<ErrorResponse>> handleRuntimeException(RuntimeException e) {
ErrorResponse error = new ErrorResponse();
error.setCode(500);
error.setMessage(e.getMessage());
return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error));
}
/**
* 处理参数异常
*/
@ExceptionHandler(IllegalArgumentException.class)
public Mono<ResponseEntity<ErrorResponse>> handleIllegalArgumentException(IllegalArgumentException e) {
ErrorResponse error = new ErrorResponse();
error.setCode(400);
error.setMessage("参数错误: " + e.getMessage());
return Mono.just(ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error));
}
}

View File

@@ -1,44 +0,0 @@
package com.bamanker.dailylove.service;
import com.bamanker.dailylove.domain.TianXinReqParam;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
/**
* 天行数据第三方接口
* @author baman
*/
@Component
@FeignClient(value = "TianXinDataRemoteClient",url = "${tianxin.server}")
public interface DataRemoteClient {
@GetMapping(value = "/tianqi/index",
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
String getWeather(@SpringQueryMap TianXinReqParam param);
@GetMapping(value = "/caihongpi/index",
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
String getRainbow(@SpringQueryMap TianXinReqParam param);
@GetMapping(value = "/ensentence/index",
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
String getDailyEnglish(@SpringQueryMap TianXinReqParam param);
@GetMapping(value = "/qiaomen/index",
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
String getTips(@SpringQueryMap TianXinReqParam param);
@GetMapping(value = "/zaoan/index",
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
String getMorning(@SpringQueryMap TianXinReqParam param);
@GetMapping(value = "/wanan/index",
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
String getNight(@SpringQueryMap TianXinReqParam param);
}

View File

@@ -0,0 +1,89 @@
package com.bamanker.dailylove.service;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
@Service
public class DataRemoteService {
final
WebClient webClient;
public DataRemoteService(@Qualifier("dateRemoteClient") WebClient dataRemoteService) {
this.webClient = dataRemoteService;
}
public Mono<String> getWeather(String key, String city, String type) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/tianqi/index")
.queryParam("key", key)
.queryParam("city", city)
.queryParam("type", type)
.build())
.retrieve()
.bodyToMono(String.class);
}
public Mono<String> getRainbow(String key, String city, String type) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/caihongpi/index")
.queryParam("key", key)
.queryParam("city", city)
.queryParam("type", type)
.build())
.retrieve()
.bodyToMono(String.class);
}
public Mono<String> getDailyEnglish(String key, String city, String type) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/ensentence/index")
.queryParam("key", key)
.queryParam("city", city)
.queryParam("type", type)
.build())
.retrieve()
.bodyToMono(String.class);
}
public Mono<String> getTips(String key, String city, String type) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/qiaomen/index")
.queryParam("key", key)
.queryParam("city", city)
.queryParam("type", type)
.build())
.retrieve()
.bodyToMono(String.class);
}
public Mono<String> getMorning(String key, String city, String type) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/zaoan/index")
.queryParam("key", key)
.queryParam("city", city)
.queryParam("type", type)
.build())
.retrieve()
.bodyToMono(String.class);
}
public Mono<String> getNight(String key, String city, String type) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/wanan/index")
.queryParam("key", key)
.queryParam("city", city)
.queryParam("type", type)
.build())
.retrieve()
.bodyToMono(String.class);
}
}

View File

@@ -1,21 +0,0 @@
package com.bamanker.dailylove.service;
import com.bamanker.dailylove.domain.ResultVo;
import com.bamanker.dailylove.domain.WechatTokenParam;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Component
@FeignClient(value = "WechatRequestClient", url = "https://api.weixin.qq.com/cgi-bin")
public interface WechatRequestClient {
@GetMapping("/token")
String getAccessToken(@SpringQueryMap WechatTokenParam param);
@PostMapping("/message/template/send?access_token={token}")
String sendMsg(ResultVo resultVo, @RequestParam("token") String token);
}

View File

@@ -0,0 +1,39 @@
package com.bamanker.dailylove.service;
import com.bamanker.dailylove.domain.ResultVo;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
@Service
public class WechatRequestService {
final
WebClient webClient;
public WechatRequestService(@Qualifier("wechatWebClient") WebClient dateRemoteWebClient) {
this.webClient = dateRemoteWebClient;
}
public Mono<String> getAccessToken(String grant_type,String appid,String secret){
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/token")
.queryParam("grant_type", grant_type)
.queryParam("appid", appid)
.queryParam("secret", secret)
.build())
.retrieve()
.bodyToMono(String.class);
}
public Mono<String> sendMsg(String token, ResultVo resultVo){
return webClient.post()
.uri("/message/template/send?access_token={token}", token)
.bodyValue(resultVo)
.retrieve()
.bodyToMono(String.class);
}
}

View File

@@ -5,13 +5,11 @@ import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.bamanker.dailylove.config.DailyLoveConfigure;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.Strings;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.util.Calendar;
import java.util.Date;
@@ -31,7 +29,7 @@ public class DataUtils {
ChineseDate chineseBir = new ChineseDate(DateUtil.parseDate(DailyLoveConfigure.Boy_Birthday));
log.info("生日的农历日期是:{}", chineseBir);
//截取日、月
String[] strings = Strings.split(boyBirthday, '-');
// String[] strings = Strings.split(boyBirthday, '-');
int chineseMonth = chineseBir.getMonth();
int chineseDay = chineseBir.getDay();
//获取当前日期的年

View File

@@ -22,7 +22,7 @@ wechat:
app-secret: 834078bb149409bfca4fe693ea7c4c1c
# ME: oo5bL6bK_4TC0tb-Wa5oiugTPVeQ
#LILI: oo5bL6QafHJa9zQNYKS0fIhFC0zM
open-id: oo5bL6QafHJa9zQNYKS0fIhFC0zM
open-id: oo5bL6bK_4TC0tb-Wa5oiugTPVeQ
template-id-morning: dWNAL-ZOzpBhnByFoTamt9DlJQYLB5z3ldKLvQstyU4
template-id-night: oraLiXC-8740stYc1a7mpzUFHiAIRaM3JikqibZ2grE
@@ -54,8 +54,7 @@ tianxin:
logging:
level:
com.bamanker.dailylove.service: debug #指定openfeign日志以什么级别监控哪个接口可多个
reactor.netty.http.client: debug
scanclass: false
# Actuator 配置

View File

@@ -1,29 +1,29 @@
package com.bamanker.dailylove;
import com.bamanker.dailylove.config.DailyLoveConfigure;
import com.bamanker.dailylove.domain.DataItem;
import com.bamanker.dailylove.domain.TianXinReqParam;
import com.bamanker.dailylove.domain.Weather;
import com.bamanker.dailylove.service.DataRemoteClient;
import com.bamanker.dailylove.utils.DataUtils;
import com.bamanker.dailylove.service.DataRemoteService;
import com.bamanker.dailylove.service.WechatRequestService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import com.bamanker.dailylove.domain.*;
import tools.jackson.databind.json.JsonMapper;
@SpringBootTest
@Slf4j
class DailyLoveApplicationTests {
//
// @Resource
// DataRemoteClient dataRemoteClient;
//
// @Autowired
// ObjectMapper mapper;
@Resource
DataRemoteService dataRemoteService;
@Resource
WechatRequestService wechatRequestService;
@Autowired
JsonMapper mapper;
//
// String remark = "❤";
@@ -104,7 +104,7 @@ class DailyLoveApplicationTests {
//
// @Test
// void test2() {
//
// ResultVo resultVo = ResultVo.initializeResultVo(DailyLoveConfigure.Open_ID,
// DailyLoveConfigure.Template_ID_Night,
// DailyLoveConfigure.Color_Top);
@@ -113,8 +113,137 @@ class DailyLoveApplicationTests {
// param1.setKey(DailyLoveConfigure.TianXin_Key);
// param1.setCity(DailyLoveConfigure.City_ID);
// param1.setType("7");
// String weatherResp = dataRemoteClient.getWeather(param1);
//// log.info("weather:{}", weatherResp);
// Mono<String> weatherRespMono = dataRemoteService.getWeather(param1.getKey(), param1.getCity(), param1.getType());
// Mono<ResultVo> resultVoMono1 = weatherRespMono
// .map(respJson -> mapper.readTree(respJson)
// .get("result")
// .get("area")
// .toString())
// .flatMap(city -> {
// resultVo.setAttribute("city", new DataItem(city, DailyLoveConfigure.Color_city));
// return Mono.just(resultVo);
// });
// Mono<ResultVo> resultVoMono2 = weatherRespMono
// .map(respJson -> mapper.readTree(respJson)
// .get("result")
// .get("list")
// .get(1))
// .map(respJson -> mapper.treeToValue(respJson, Weather.class))
// .flatMap(weather -> {
// resultVo.setAttribute("tomorrow", new DataItem(weather.getDate() + " " + weather.getWeek(), DailyLoveConfigure.Color_tomorrow));
// resultVo.setAttribute("weather", new DataItem(weather.getWeather(), DailyLoveConfigure.Color_weather));
// resultVo.setAttribute("min_temperature", new DataItem(weather.getLowest(), DailyLoveConfigure.Color_minTem));
// resultVo.setAttribute("max_temperature", new DataItem(weather.getHighest(), DailyLoveConfigure.Color_maxTem));
// resultVo.setAttribute("quality", new DataItem(weather.getVis(), DailyLoveConfigure.Color_quality));
// return Mono.just(resultVo);
// });
//// Mono<Tuple2<ResultVo, ResultVo>> zip = Mono.zip(resultVoMono1, resultVoMono);
//
//
// TianXinReqParam param2 = new TianXinReqParam();
// param2.setKey(DailyLoveConfigure.TianXin_Key);
//
// Mono<ResultVo> resultVoMono3 = dataRemoteService.getTips(param2.getKey(), param2.getCity(), param2.getType())
// .map(respJson -> mapper.readTree(respJson)
// .get("result")
// .get("content").asString())
// .flatMap(tips -> {
// resultVo.setAttribute("tips", new DataItem(tips, DailyLoveConfigure.Color_tips));
// return Mono.just(resultVo);
// });
// Mono<ResultVo> resultVoMono4 = dataRemoteService.getNight(param2.getKey(), param2.getCity(), param2.getType())
// .map(respJson -> mapper.readTree(respJson)
// .get("result")
// .get("content").asString())
// .flatMap(night -> {
// resultVo.setAttribute("night", new DataItem(night, DailyLoveConfigure.Color_night));
// return Mono.just(resultVo);
// });
// Mono<ResultVo> resultVoMono5 = dataRemoteService.getRainbow(param2.getKey(), param2.getCity(), param2.getType())
// .map(respJson -> mapper.readTree(respJson)
// .get("result")
// .get("content").asString())
// .flatMap(rainbow -> {
// resultVo.setAttribute("rainbow", new DataItem(rainbow, DailyLoveConfigure.Color_dailyCn));
// return Mono.just(resultVo);
// });
//
// Mono<ResultVo> resultVoMono = Mono.zip(resultVoMono1, resultVoMono2, resultVoMono3, resultVoMono4, resultVoMono5)
// .flatMap(new Function<Tuple5<ResultVo, ResultVo, ResultVo, ResultVo, ResultVo>, Mono<? extends ResultVo>>() {
// @Override
// public Mono<? extends ResultVo> apply(Tuple5<ResultVo, ResultVo, ResultVo, ResultVo, ResultVo> tuple) {
// return Mono.just(tuple.getT1());
// }
// });
//
// ChineseDate chineseDate = new ChineseDate(DateUtil.parseDate(LocalDate.now().toString()));
// String festival = chineseDate.getFestivals();
// String term = chineseDate.getTerm();
// resultVo.setAttribute("lunar", new DataItem(chineseDate.toString(), DailyLoveConfigure.Color_chineseDate));
// resultVo.setAttribute("festival", new DataItem(festival + " " + term, DailyLoveConfigure.Color_festival));
//
//
// int girlBirthdays = DataUtils.getBirthdays(DailyLoveConfigure.Girl_Birthday);
// log.info("gbir_days:{}", girlBirthdays);
// resultVo.setAttribute("gbir_day", new DataItem(girlBirthdays - 1 + "", DailyLoveConfigure.Color_gbir));
//
// int boyBirthdays = DataUtils.getChineseBirthdays(DailyLoveConfigure.Boy_Birthday);
// log.info("bbir_days:{}", boyBirthdays);
// resultVo.setAttribute("bbir_day", new DataItem(boyBirthdays - 1 + "", DailyLoveConfigure.Color_bbir));
//
// int catBirthdays = DataUtils.getBirthdays(DailyLoveConfigure.Cat_Birthday);
// log.info("cbir_days:{}", catBirthdays);
// resultVo.setAttribute("cbir_day", new DataItem(catBirthdays - 1 + "", DailyLoveConfigure.Color_cbir));
//
// String words = "普通的一天";
//
// if (DataUtils.getBirthdays(DailyLoveConfigure.Love_Day) == 1) {
// words = "明天是恋爱周年纪念日!永远爱你~mua";
// } else if ((DataUtils.getDayDiff(DailyLoveConfigure.Love_Day)) % 100 == 99) {
// words = "明天是恋爱百日纪念日!提前庆祝哦~";
// } else if (DataUtils.getBirthdays(DailyLoveConfigure.Wedding_Day) == 1) {
// words = "明天是结婚周年纪念日!提前庆祝哦~";
// } else if (girlBirthdays == 1) {
// words = "明天是lili大宝贝的生日啦";
// } else if (boyBirthdays == 1) {
// words = "明天是菘菘的生日!别忘了哦~";
// } else if (catBirthdays == 1) {
// words = "明天是小离谱的生日!别忘了小鱼干!";
// }
//
// resultVo.setAttribute("words", new DataItem(words, DailyLoveConfigure.Color_remark));
//
// int loveDays = DataUtils.getDayDiff(DailyLoveConfigure.Love_Day);
// log.info("love_days:{}", loveDays);
// resultVo.setAttribute("love_day", new DataItem(loveDays + 1 + "", DailyLoveConfigure.Color_loveDay));
//
// int weddingDays = DataUtils.getDayDiff(DailyLoveConfigure.Wedding_Day);
// log.info("wedding_days:{}", weddingDays);
// resultVo.setAttribute("wedding_day", new DataItem(weddingDays + 1 + "", DailyLoveConfigure.Color_weddingDay));
//
// resultVoMono.flatMap(new Function<ResultVo, Mono<?>>() {
// @Override
// public Mono<?> apply(ResultVo resultVo) {
// return Mono.just(resultVo);
// }
// }).log().block();
//
// WechatTokenParam param3 = new WechatTokenParam();
// param3.setAppid(DailyLoveConfigure.App_ID);
// param3.setSecret(DailyLoveConfigure.App_Secret);
//
// String accessToken = wechatRequestService.getAccessToken(param3.getGrant_type(), param3.getAppid(), param3.getSecret())
// .map(respJson -> {
// return mapper.readTree(respJson)
// .get("access_token").asString();
// }).log().block();
// wechatRequestService.sendMsg(accessToken, resultVo).log().block();
// String tips = mapper.readTree(tipsResp).get("result").get("content").asString();
// log.info("weather:{}", weatherResp);
// JsonNode weatherJson = mapper.readTree(weatherResp).get("result").get("list").get(1);
// System.out.println("-----------------------------");
// System.out.println(weatherJson);
@@ -238,6 +367,6 @@ class DailyLoveApplicationTests {
// log.info("resultVo:{}", resultVo);
// }
}
//}