前言
通过商品渠道新增咪咕埋点功能:当用户通过小西访问了咪咕相关的商品时,需要把这访问记录下来,发送给咪咕方。
实现
打算在咪咕商品api里写实现逻辑。因为小西是访问的第三方接口,可能会出现一些不可控因素,如:有可能抛出异常,也可能响应时间过长。因此采用线程异步方式,防止断开连接。关于线程异步,可参考:在Java中通过线程池实现异步执行
GoodsSpuMiGuController
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/goodsspu/migu")
@Api(value = "migu", tags = "咪咕快游spu商品接口API")
public class GoodsSpuMiGuController {
private final GoodsSpuMiGuService goodsSpuMiGuService;
private final AccessStatisticsComponentService accessStatisticsComponentService;
/**
* @Description: 通过商品渠道查询咪咕快游商品
*/
@ApiOperation(value = "通过商品渠道查询咪咕快游商品,4表示咪咕会员,5表示咪咕时长包")
@GetMapping("/getGoodsSpuMiGuByChannel/{channel}")
public R getGoodsSpuMiGuByChannel(@PathVariable("channel") String channel) {
//发送访问记录给咪咕方
ThreadUtil.execAsync(() -> accessStatisticsComponentService.sendAccessStatistics());
return goodsSpuMiGuService.getGoodsSpuMiGuByChannel(channel);
}
}
AccessStatisticsComponentService
@Slf4j
@Service
@RestController
@AllArgsConstructor
public class AccessStatisticsComponentService {
private final MiGuConfig miguConfig;
/**
* @Description: 发送访问记录给咪咕方
*/
public void sendAccessStatistics() {
try {
String userPhone = ThirdSessionHolder.getThirdSession().getPhone();
log.info("userPhone值! userPhone={}",userPhone);
LocalDateTime operationTime = LocalDateTime.now();
JSONObject queryReq = new JSONObject();
queryReq.set("userPhone", userPhone);
queryReq.set("operationTime", operationTime);
String url = miguConfig.getCollectMallBuryPointsUrl();
log.info("sendAccessStatistics url={}",url);
String respStr = HttpUtil.createPost(url).setConnectionTimeout(10000).setReadTimeout(10000)
.header(Header.CONTENT_TYPE, ContentType.JSON.getValue()).body(queryReq.toString()).execute().body();
if(StrUtil.isNotBlank(respStr)){
log.info("发送访问记录给咪咕方成功!");
}
} catch (Exception e) {
log.error("发送访问记录给咪咕方失败! ex={}", e.getMessage(), e);
}
}
}
问题
代码调试时,出现了SocketTimeoutException:connect timed out
问题,如下图所示:
解决办法,可参考:【异常】原来提示SocketTimeoutException:connect timed out还可能是外部因素导致