Commit 89dd6eae by 王欣伟

车型数据同步从页面爬取改为接口数据解析

1 parent eea9f43c
...@@ -15,12 +15,12 @@ import org.springframework.context.annotation.ComponentScan; ...@@ -15,12 +15,12 @@ import org.springframework.context.annotation.ComponentScan;
@ComponentScan("com.bs.cardata") @ComponentScan("com.bs.cardata")
@ForestScan("com.bs.cardata") @ForestScan("com.bs.cardata")
@SpringBootApplication @SpringBootApplication
public class LinkWeChatCarDataApplication { public class BsApplication {
public static void main(String[] args) { public static void main(String[] args) {
new SpringApplicationBuilder(LinkWeChatCarDataApplication.class) new SpringApplicationBuilder(BsApplication.class)
// .properties("spring.config.name:bootstrap", "config/run/bootstrap.yml") // .properties("spring.config.name:bootstrap", "config/run/bootstrap.yml")
.properties("spring.application.name=linkwe-car-data") .properties("spring.application.name=bs-car-data")
.build().run(args); .build().run(args);
System.out.println("(♥◠‿◠)ノ゙ linkwe-car-data启动成功 ლ(´ڡ`ლ)゙ "); System.out.println("(♥◠‿◠)ノ゙ bs-car-data启动成功 ლ(´ڡ`ლ)゙ ");
} }
} }
...@@ -32,4 +32,14 @@ public class CarSysConfig { ...@@ -32,4 +32,14 @@ public class CarSysConfig {
* 对应旧系统配置:carauto.img.host.name * 对应旧系统配置:carauto.img.host.name
*/ */
private String carautoImgeHost; private String carautoImgeHost;
/**
* 汽车之家 车系价格获取
*/
private String priceServerUrl;
/**
* 汽车之家 车型详细配置获取接口
*/
private String cartypeParamsConfigUrl;
} }
...@@ -42,4 +42,24 @@ public class ServiceConstants { ...@@ -42,4 +42,24 @@ public class ServiceConstants {
public static final String CARTYPE_UPLOADURL_OBJ = "carsimple.cartype.upload.url.object"; public static final String CARTYPE_UPLOADURL_OBJ = "carsimple.cartype.upload.url.object";
/* 车辆信息-end */ /* 车辆信息-end */
/**
* 清除缓存接口密钥(建议移至nacos配置中心管理)
*/
public static final String CLEAR_CACHE_SECRET = "bs_cardata_clear_cache_2024";
/**
* 清除缓存nonce redis key前缀
*/
public static final String CLEAR_CACHE_NONCE_KEY = "cardata:clear_cache:nonce:";
/**
* 时间戳有效窗口(毫秒),5分钟
*/
public static final long TIMESTAMP_VALID_WINDOW_MS = 5 * 60 * 1000L;
/**
* nonce在Redis中的过期时间(秒),10分钟
*/
public static final int NONCE_EXPIRE_SECONDS = 10 * 60;
} }
package com.bs.cardata.controller; package com.bs.cardata.controller;
import com.google.protobuf.ServiceException; import com.google.protobuf.ServiceException;
import com.bs.cardata.constant.ServiceConstants;
import com.bs.cardata.dto.CarBrandHierarchyDto; import com.bs.cardata.dto.CarBrandHierarchyDto;
import com.bs.cardata.dto.CarTypeDto; import com.bs.cardata.dto.CarTypeDto;
import com.bs.cardata.service.CarbrandService; import com.bs.cardata.service.CarbrandService;
import com.bs.cardata.service.CartypeService; import com.bs.cardata.service.CartypeService;
import com.bs.common.annotation.Log; import com.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController; import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.redis.RedisService;
import com.bs.common.enums.BusinessType; import com.bs.common.enums.BusinessType;
import com.bs.common.utils.sign.Md5Utils;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -36,6 +40,9 @@ public class CarDataApiController extends BaseController { ...@@ -36,6 +40,9 @@ public class CarDataApiController extends BaseController {
@Autowired @Autowired
private CartypeService cartypeService; private CartypeService cartypeService;
@Autowired
private RedisService redisService;
//@ApiOperation(value = "新增商品", httpMethod = "POST") //@ApiOperation(value = "新增商品", httpMethod = "POST")
@Log(title = "获取所有车辆品牌和车系数据", businessType = BusinessType.SELECT) @Log(title = "获取所有车辆品牌和车系数据", businessType = BusinessType.SELECT)
@GetMapping("/allcar") @GetMapping("/allcar")
...@@ -55,4 +62,58 @@ public class CarDataApiController extends BaseController { ...@@ -55,4 +62,58 @@ public class CarDataApiController extends BaseController {
return cartypeService.getCarTypeListBySeriesId(csId); return cartypeService.getCarTypeListBySeriesId(csId);
} }
/**
* 清除车辆数据缓存
* <p>
* 加密参数生成规则:
* 1. 生成随机 nonce(UUID)
* 2. 获取当前时间戳 timestamp(毫秒)
* 3. 拼接明文:nonce + timestamp + secretKey
* 4. 对明文做 MD5 得到 token
* <p>
* 调用示例:GET /common/api/clearCache?token=xxx&timestamp=xxx&nonce=xxx
*/
@Log(title = "清除车辆数据缓存", businessType = BusinessType.OTHER)
@GetMapping("/clearCache")
@Operation(summary = "清除车辆数据缓存(需加密参数,一次性使用)")
public AjaxResult clearCache(@RequestParam("token") String token,
@RequestParam("timestamp") String timestamp,
@RequestParam("nonce") String nonce) {
// 1. 校验时间戳是否在有效窗口内
long requestTime;
try {
requestTime = Long.parseLong(timestamp);
} catch (NumberFormatException e) {
return AjaxResult.error("时间戳格式不正确");
}
long now = System.currentTimeMillis();
if (Math.abs(now - requestTime) > ServiceConstants.TIMESTAMP_VALID_WINDOW_MS) {
return AjaxResult.error("请求已过期,时间戳超出有效窗口");
}
// 2. 校验 nonce 是否已被使用(保证参数只能使用一次)
String nonceKey = ServiceConstants.CLEAR_CACHE_NONCE_KEY + nonce;
if (Boolean.TRUE.equals(redisService.hasKey(nonceKey))) {
return AjaxResult.error("该加密参数已被使用,请重新生成");
}
// 3. 校验签名是否正确
String plainText = nonce + timestamp + ServiceConstants.CLEAR_CACHE_SECRET;
String expectedToken = Md5Utils.getMD532Str(plainText);
if (!expectedToken.equals(token)) {
return AjaxResult.error("加密参数校验失败");
}
// 4. 标记 nonce 为已使用,设置过期时间(需大于时间戳有效窗口,防止重放)
redisService.setCacheObject(nonceKey, "1",
ServiceConstants.NONCE_EXPIRE_SECONDS,
java.util.concurrent.TimeUnit.SECONDS);
// 5. 清除车辆数据相关缓存
redisService.deleteObject(ServiceConstants.CAR_BRAND_SELECTED_COMPLETE_CACHE_KEY);
logger.info("车辆数据缓存已清除,nonce={}", nonce);
return AjaxResult.success("缓存清除成功", null);
}
} }
\ No newline at end of file \ No newline at end of file
...@@ -13,7 +13,7 @@ import java.util.List; ...@@ -13,7 +13,7 @@ import java.util.List;
* *
* @author MyEclipse Persistence Tools * @author MyEclipse Persistence Tools
*/ */
@TableName(value = "platform_carbrand") @TableName(value = "bs_carbrand")
public class Carbrand implements java.io.Serializable { public class Carbrand implements java.io.Serializable {
// Fields // Fields
......
...@@ -12,7 +12,7 @@ import java.util.Date; ...@@ -12,7 +12,7 @@ import java.util.Date;
* *
* @author MyEclipse Persistence Tools * @author MyEclipse Persistence Tools
*/ */
@TableName("platform_carseries") @TableName("bs_carseries")
public class Carseries implements java.io.Serializable { public class Carseries implements java.io.Serializable {
// Fields // Fields
......
...@@ -10,7 +10,7 @@ import java.util.Date; ...@@ -10,7 +10,7 @@ import java.util.Date;
/** /**
* 汽车车型实体类 * 汽车车型实体类
*/ */
@TableName("platform_cartype") @TableName("bs_cartype")
public class Cartype implements java.io.Serializable { public class Cartype implements java.io.Serializable {
@TableId(value = "id", type = IdType.AUTO) @TableId(value = "id", type = IdType.AUTO)
......
...@@ -28,7 +28,7 @@ public class CarInfoJob { ...@@ -28,7 +28,7 @@ public class CarInfoJob {
public void execute() { public void execute() {
try { try {
log.info("job:车辆信息同步开始"); log.info("job:车辆信息同步开始");
List<String> baseUrlList = DataUtils.getBaseUrlList(); /*List<String> baseUrlList = DataUtils.getBaseUrlList();
for (String baseurl : baseUrlList) { for (String baseurl : baseUrlList) {
try { try {
log.info("车辆信息同步:" + baseurl + " 启动。"); log.info("车辆信息同步:" + baseurl + " 启动。");
...@@ -36,7 +36,17 @@ public class CarInfoJob { ...@@ -36,7 +36,17 @@ public class CarInfoJob {
} catch (Exception e) { } catch (Exception e) {
log.info("需要计算的行程数据获取异常:" + baseurl + e.getMessage()); log.info("需要计算的行程数据获取异常:" + baseurl + e.getMessage());
} }
}*/
// 2026-01-27: 切换到新接口,一次性获取所有数据
String newApiUrl = "https://www.autohome.com.cn/web-main/car/web/price/treeMenu?extendseries=1";
try {
log.info("车辆信息同步:" + newApiUrl + " 启动。");
carDataService.syncCarInfo(newApiUrl);
} catch (Exception e) {
log.info("车辆信息同步异常:" + newApiUrl + e.getMessage());
} }
log.info("job:车辆信息同步结束"); log.info("job:车辆信息同步结束");
} catch (Exception e) { } catch (Exception e) {
log.info("job:车辆信息同步,exception msg:" + e.getMessage()); log.info("job:车辆信息同步,exception msg:" + e.getMessage());
......
...@@ -18,8 +18,6 @@ public interface CarDataService { ...@@ -18,8 +18,6 @@ public interface CarDataService {
*/ */
void syncCarInfo(String baseurl); void syncCarInfo(String baseurl);
void getOldCarSeries(String seriesId, String dataId, JSONObject serTypeJson);
void getCarSeriesInfoV2(String seriesId, JSONObject serTypeJson); void getCarSeriesInfoV2(String seriesId, JSONObject serTypeJson);
} }
\ No newline at end of file \ No newline at end of file
...@@ -49,6 +49,7 @@ public class CarSyncServiceImpl implements CarSyncService { ...@@ -49,6 +49,7 @@ public class CarSyncServiceImpl implements CarSyncService {
if (carBrand == null) { if (carBrand == null) {
carBrand = createCarBrand(ppJson, childPP); carBrand = createCarBrand(ppJson, childPP);
} else { } else {
carBrand.setUpdateTime(new Date());
if ((carBrand.getParentId()==null || carBrand.getParentId().intValue()==10000000) && ppJson.getIntValue(ServiceConstants.carBrandParentIdKey)>0) { if ((carBrand.getParentId()==null || carBrand.getParentId().intValue()==10000000) && ppJson.getIntValue(ServiceConstants.carBrandParentIdKey)>0) {
carBrand.setParentId(ppJson.getIntValue(ServiceConstants.carBrandParentIdKey)); carBrand.setParentId(ppJson.getIntValue(ServiceConstants.carBrandParentIdKey));
carBrandMapper.updateById(carBrand); carBrandMapper.updateById(carBrand);
...@@ -96,6 +97,9 @@ public class CarSyncServiceImpl implements CarSyncService { ...@@ -96,6 +97,9 @@ public class CarSyncServiceImpl implements CarSyncService {
try { try {
Map<String, Object> valueMap = new HashMap<String, Object>(); Map<String, Object> valueMap = new HashMap<String, Object>();
Map<String, Object> whereMap = new HashMap<String, Object>(); Map<String, Object> whereMap = new HashMap<String, Object>();
Date currentDate = new Date();
carseries = carSeriesMapper.getCarSeriesInfo(cxJson.get("id").toString()); carseries = carSeriesMapper.getCarSeriesInfo(cxJson.get("id").toString());
if (carseries == null) { if (carseries == null) {
carseries = new Carseries(); carseries = new Carseries();
...@@ -103,7 +107,7 @@ public class CarSyncServiceImpl implements CarSyncService { ...@@ -103,7 +107,7 @@ public class CarSyncServiceImpl implements CarSyncService {
carseries.setBrandCode(String.valueOf(brandId)); carseries.setBrandCode(String.valueOf(brandId));
carseries.setCarseries(cxJson.get("cx_name").toString()); carseries.setCarseries(cxJson.get("cx_name").toString());
carseries.setSeriesLetter(Pinyin4JUtil.getFirstLetter(cxJson.get("cx_name").toString())); carseries.setSeriesLetter(Pinyin4JUtil.getFirstLetter(cxJson.get("cx_name").toString()));
carseries.setCreateTime(new Date()); carseries.setCreateTime(currentDate);
carseries.setLastOperatorId(ServiceConstants.lastOperatorId); carseries.setLastOperatorId(ServiceConstants.lastOperatorId);
carseries.setLastOperatorName(ServiceConstants.lastOperatorName); carseries.setLastOperatorName(ServiceConstants.lastOperatorName);
carseries.setOperatorType(ServiceConstants.operatorType); carseries.setOperatorType(ServiceConstants.operatorType);
...@@ -113,6 +117,7 @@ public class CarSyncServiceImpl implements CarSyncService { ...@@ -113,6 +117,7 @@ public class CarSyncServiceImpl implements CarSyncService {
carseries.setHigherPrice(cxJson.getDouble(CAR_SERIES_HIGHER_PRICE)); carseries.setHigherPrice(cxJson.getDouble(CAR_SERIES_HIGHER_PRICE));
int res = carSeriesMapper.insert(carseries); int res = carSeriesMapper.insert(carseries);
if (carseries.getCsid() != null) { if (carseries.getCsid() != null) {
carseries.setUpdateTime(currentDate);
carseries.setCarseriesCode(String.valueOf(carseries.getCsid())); carseries.setCarseriesCode(String.valueOf(carseries.getCsid()));
carSeriesMapper.updateById(carseries); carSeriesMapper.updateById(carseries);
} }
...@@ -135,6 +140,7 @@ public class CarSyncServiceImpl implements CarSyncService { ...@@ -135,6 +140,7 @@ public class CarSyncServiceImpl implements CarSyncService {
updateFlag = true; updateFlag = true;
} }
if (updateFlag){ if (updateFlag){
carseries.setUpdateTime(currentDate);
carSeriesMapper.updateById(carseries); carSeriesMapper.updateById(carseries);
} }
} }
...@@ -191,6 +197,8 @@ public class CarSyncServiceImpl implements CarSyncService { ...@@ -191,6 +197,8 @@ public class CarSyncServiceImpl implements CarSyncService {
dctJson = new JSONObject(); dctJson = new JSONObject();
} }
Date currentDate = new Date();
// 能源类型 // 能源类型
Integer ennergyType = null; Integer ennergyType = null;
String energyDesc = ""; String energyDesc = "";
...@@ -275,9 +283,11 @@ public class CarSyncServiceImpl implements CarSyncService { ...@@ -275,9 +283,11 @@ public class CarSyncServiceImpl implements CarSyncService {
carType.setAutohomeId(trJson.get("Id").toString()); carType.setAutohomeId(trJson.get("Id").toString());
carType.setStatus(0); carType.setStatus(0);
carType.setIdentifyingPhoto(cxImageUrl); carType.setIdentifyingPhoto(cxImageUrl);
carType.setCreateTime(currentDate);
int res = carTypeMapper.insert(carType); int res = carTypeMapper.insert(carType);
if (res > 0) { if (res > 0) {
carType.setCarTypeId(carType.getId()); carType.setCarTypeId(carType.getId());
carType.setUpdateTime(currentDate);
carTypeMapper.updateById(carType); carTypeMapper.updateById(carType);
} }
} else { } else {
...@@ -320,7 +330,7 @@ public class CarSyncServiceImpl implements CarSyncService { ...@@ -320,7 +330,7 @@ public class CarSyncServiceImpl implements CarSyncService {
} }
if (updateFlag) { if (updateFlag) {
carType.setUpdateTime(new Date()); carType.setUpdateTime(currentDate);
carTypeMapper.updateById(carType); carTypeMapper.updateById(carType);
} }
} }
...@@ -368,6 +378,7 @@ public class CarSyncServiceImpl implements CarSyncService { ...@@ -368,6 +378,7 @@ public class CarSyncServiceImpl implements CarSyncService {
ppJson.put(ServiceConstants.carBrandParentIdKey, -2); ppJson.put(ServiceConstants.carBrandParentIdKey, -2);
Carbrand = createCarBrand(ppJson, ppJson.getString("name")); Carbrand = createCarBrand(ppJson, ppJson.getString("name"));
} else { } else {
Carbrand.setUpdateTime(new Date());
udpateCarbrandAndPhotoImg(Carbrand, ppJson, null); udpateCarbrandAndPhotoImg(Carbrand, ppJson, null);
} }
return Carbrand.getBid(); return Carbrand.getBid();
...@@ -376,14 +387,15 @@ public class CarSyncServiceImpl implements CarSyncService { ...@@ -376,14 +387,15 @@ public class CarSyncServiceImpl implements CarSyncService {
// 创建品牌信息 // 创建品牌信息
private Carbrand createCarBrand(JSONObject ppJson, String brandName) { private Carbrand createCarBrand(JSONObject ppJson, String brandName) {
Carbrand carBrand = new Carbrand(); Carbrand carBrand = new Carbrand();
Date currentDate = new Date();
carBrand.setBrand(brandName); carBrand.setBrand(brandName);
carBrand.setIdentifyingPhoto(ppJson.get("upload_url").toString()); carBrand.setIdentifyingPhoto(ppJson.getString("upload_url"));
carBrand.setBraLetter(Pinyin4JUtil.getFirstLetter(brandName)); carBrand.setBraLetter(Pinyin4JUtil.getFirstLetter(brandName));
carBrand.setCreateTime(new Date()); carBrand.setCreateTime(currentDate);
carBrand.setLastOperatorId(String.valueOf(ServiceConstants.lastOperatorId)); carBrand.setLastOperatorId(String.valueOf(ServiceConstants.lastOperatorId));
carBrand.setLastOperatorName(ServiceConstants.lastOperatorName); carBrand.setLastOperatorName(ServiceConstants.lastOperatorName);
carBrand.setOperatorType(ServiceConstants.operatorType); carBrand.setOperatorType(ServiceConstants.operatorType);
carBrand.setAutohomeId(ppJson.get("id").toString()); carBrand.setAutohomeId(ppJson.getString("id"));
carBrand.setIsUsed(0); carBrand.setIsUsed(0);
if (ppJson.getIntValue(ServiceConstants.carBrandParentIdKey)>0) { if (ppJson.getIntValue(ServiceConstants.carBrandParentIdKey)>0) {
carBrand.setParentId(ppJson.getIntValue(ServiceConstants.carBrandParentIdKey)); carBrand.setParentId(ppJson.getIntValue(ServiceConstants.carBrandParentIdKey));
...@@ -393,6 +405,7 @@ public class CarSyncServiceImpl implements CarSyncService { ...@@ -393,6 +405,7 @@ public class CarSyncServiceImpl implements CarSyncService {
int res = carBrandMapper.insert(carBrand); int res = carBrandMapper.insert(carBrand);
if (carBrand.getBid() != null) { if (carBrand.getBid() != null) {
carBrand.setBrandCode(String.valueOf(carBrand.getBid())); carBrand.setBrandCode(String.valueOf(carBrand.getBid()));
carBrand.setUpdateTime(currentDate);
carBrandMapper.updateById(carBrand); carBrandMapper.updateById(carBrand);
} }
return carBrand; return carBrand;
......
...@@ -81,7 +81,7 @@ public class CarTypeJsonDeal { ...@@ -81,7 +81,7 @@ public class CarTypeJsonDeal {
* @param carSeriseViewJson * @param carSeriseViewJson
* @return * @return
*/ */
public static List<JSONObject> getOnSaleList(JSONObject carSeriseViewJson, String configOne, String seriesId) { public static List<JSONObject> getOnSaleList(String serverUrl, JSONObject carSeriseViewJson, String configOne, String seriesId) {
List<JSONObject> resultList = new ArrayList<>(); List<JSONObject> resultList = new ArrayList<>();
try { try {
...@@ -121,7 +121,7 @@ public class CarTypeJsonDeal { ...@@ -121,7 +121,7 @@ public class CarTypeJsonDeal {
cxiJson.put("Price", priceJson.getString("guidPrice")); cxiJson.put("Price", priceJson.getString("guidPrice"));
cxiJson.put("Price2Sc", priceJson.getString("lowerPrice")); cxiJson.put("Price2Sc", priceJson.getString("lowerPrice"));
cxiJson.put("seriesId", seriesId); cxiJson.put("seriesId", seriesId);
String cxDetail = CrawlUtils.getCarTypeDetailInfo(authomeId, seriesId); String cxDetail = CrawlUtils.getCarTypeDetailInfoNew(serverUrl, authomeId, seriesId);
cxiJson.put("cxDetail", cxDetail); cxiJson.put("cxDetail", cxDetail);
resultList.add(cxiJson); resultList.add(cxiJson);
} }
......
...@@ -7,40 +7,8 @@ import org.springframework.util.StringUtils; ...@@ -7,40 +7,8 @@ import org.springframework.util.StringUtils;
public class ConvertUtils { public class ConvertUtils {
// 解析已经停产的车型数据
public static JSONObject getCXTCTR(Element trEle, String seriesId) {
/* {
"Id" : 23929,"Name" : "2016款 45 TFSI quattro运动型",
"DrivingModeName" : "前置四驱","Transmission" : "7挡双离合",
"Price" : "46.46万","Price2Sc" : "25.50-29.00万",
"Link2Sc" : "http://www.che168.com/china/aodi/aodia4l/25_29/", // 二手车
"State" : 40,"ShowParas" : true,"ShowTaxRelief" : false,
"ShowPreferential" : false,"videoid" : 0,
"GroupName" : "2.0升 涡轮增压 224马力"}
*/
JSONObject res = new JSONObject();
Elements tdElmes = trEle.getElementsByTag("td");
String cxiId = tdElmes.get(0).getElementsByTag("a").get(0).attr("href").replace("spec", "").replace("/", "");
String cxiName = tdElmes.get(0).getElementsByTag("a").get(0).text();
String cxiDetail = "http://car.autohome.com.cn/config/" + tdElmes.get(0).getElementsByTag("a").get(0).attr("href");
String guidPrice = tdElmes.get(1).text();
String price2SC = tdElmes.get(2).text();
res.put("Id", cxiId);
res.put("Name", cxiName);
res.put("DrivingModeName", "");
res.put("Transmission", "");
res.put("Price", guidPrice);
res.put("Price2Sc", price2SC);
res.put("GroupName", cxiName.subSequence(0, 4));
res.put("configUrl", cxiDetail);
res.put("seriesId", seriesId);
String cxDetail = CrawlUtils.getCarTypeDetailInfo(cxiId, seriesId);
res.put("cxDetail", cxDetail);
return res;
}
// 解析在售的车型数据 // 解析在售的车型数据
public static JSONObject getSpecActiveObject(Element specItemElem, String seriesId) { public static JSONObject getSpecActiveObject(String serverUrl, Element specItemElem, String seriesId) {
String rootClass = "name-param"; String rootClass = "name-param";
String id = specItemElem.getElementsByAttributeValue("class", rootClass).get(0).getElementsByTag("p").get(0).attr("data-gcjid"); String id = specItemElem.getElementsByAttributeValue("class", rootClass).get(0).getElementsByTag("p").get(0).attr("data-gcjid");
if (StringUtils.isEmpty(id)) { if (StringUtils.isEmpty(id)) {
...@@ -64,7 +32,7 @@ public class ConvertUtils { ...@@ -64,7 +32,7 @@ public class ConvertUtils {
cxiJson.put("Price", priceJson.getString("guidPrice")); cxiJson.put("Price", priceJson.getString("guidPrice"));
cxiJson.put("Price2Sc", priceJson.getString("lowerPrice")); cxiJson.put("Price2Sc", priceJson.getString("lowerPrice"));
cxiJson.put("seriesId", seriesId); cxiJson.put("seriesId", seriesId);
String cxDetail = CrawlUtils.getCarTypeDetailInfo(id, seriesId); String cxDetail = CrawlUtils.getCarTypeDetailInfoNew(serverUrl, id, seriesId);
cxiJson.put("cxDetail", cxDetail); cxiJson.put("cxDetail", cxDetail);
return cxiJson; return cxiJson;
} }
......
...@@ -12,7 +12,9 @@ import org.slf4j.Logger; ...@@ -12,7 +12,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map;
public class CrawlUtils { public class CrawlUtils {
...@@ -160,4 +162,118 @@ public class CrawlUtils { ...@@ -160,4 +162,118 @@ public class CrawlUtils {
return res; return res;
} }
public static String getCarTypeDetailInfoNew(String serverUrl, String specId, String seriesId) {
JSONObject resJson = new JSONObject();
// https://www.autohome.com.cn/web-main/car/param/getParamConf?mode=1&site=2&specid=76430
// String specParamUrl = PropertyConfigurer.getString("autohome.cartype.params.config.url");
String url = serverUrl + "&specid=" + specId;
try {
String jsonRes = HttpUtil.get(url);
if (StringUtils.isEmpty(jsonRes)) {
LOGGER.info("====Get_car_type_config_error==data empty==" + url);
return resJson.toString();
}
JSONObject response = JSONObject.parseObject(jsonRes);
if (response.getIntValue("returncode") != 0) {
LOGGER.info("====Get_car_type_config_error====returncode is:" + response.getIntValue("returncode"));
return resJson.toString();
}
JSONObject result = response.getJSONObject("result");
// 1. 解析titlelist,构建 itemtype -> JSONObject 的映射
JSONArray titleList = result.getJSONArray("titlelist");
// key: itemtype(如"基本参数"、"发动机"),value: 该分组下的参数JSONObject
Map<String, JSONObject> typeItemsMap = new HashMap<>();
// key: titleid,value: 所属分组的 itemtype
Map<Integer, String> titleIdToTypeMap = new HashMap<>();
// key: itemtype,value: titleid -> itemname 的映射
Map<String, Map<Integer, String>> typeTitleItemMap = new HashMap<>();
for (int i = 0; i < titleList.size(); i++) {
JSONObject titleGroup = titleList.getJSONObject(i);
String itemType = titleGroup.getString("itemtype");
if (!"基本参数".equals(itemType) && !"发动机".equals(itemType)) {
continue;
}
JSONArray items = titleGroup.getJSONArray("items");
JSONObject itemObj = new JSONObject();
Map<Integer, String> titleItemMap = new HashMap<>();
for (int j = 0; j < items.size(); j++) {
JSONObject item = items.getJSONObject(j);
int titleId = item.getIntValue("titleid");
String itemName = item.getString("itemname");
titleIdToTypeMap.put(titleId, itemType);
titleItemMap.put(titleId, itemName);
}
typeItemsMap.put(itemType, itemObj);
typeTitleItemMap.put(itemType, titleItemMap);
}
// 2. 解析datalist,根据specId匹配并提取paramconflist数据
JSONArray dataList = result.getJSONArray("datalist");
for (int i = 0; i < dataList.size(); i++) {
JSONObject dataItem = dataList.getJSONObject(i);
if (!specId.equals(dataItem.getString("specid"))) {
continue;
}
JSONArray paramConfList = dataItem.getJSONArray("paramconflist");
for (int j = 0; j < paramConfList.size(); j++) {
JSONObject paramConf = paramConfList.getJSONObject(j);
int titleId = paramConf.getIntValue("titleid");
String itemType = titleIdToTypeMap.get(titleId);
if (itemType == null) {
continue;
}
Map<Integer, String> titleItemMap = typeTitleItemMap.get(itemType);
String itemName = titleItemMap.get(titleId);
if (itemName == null || itemName.isEmpty()) {
continue;
}
// 获取值:优先取itemname,若有sublist则拼接子项
String value = paramConf.getString("itemname");
if (value == null) {
value = "";
}
JSONArray subList = paramConf.getJSONArray("sublist");
if (subList != null && !subList.isEmpty() && value.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (int k = 0; k < subList.size(); k++) {
JSONObject sub = subList.getJSONObject(k);
if (k > 0) {
sb.append("/");
}
sb.append(sub.getString("name"));
}
value = sb.toString();
}
JSONObject itemObj = typeItemsMap.get(itemType);
itemObj.put(itemName, value);
}
break;
}
// 3. 将解析结果放入resJson
for (Map.Entry<String, JSONObject> entry : typeItemsMap.entrySet()) {
resJson.put(entry.getKey(), entry.getValue());
}
} catch (Exception e) {
LOGGER.error("====Get_car_type_config_exception====" + e.getMessage(), e);
}
return resJson.toString();
}
} }
spring: spring:
profiles:
active: local
---
spring:
config: config:
activate: activate:
on-profile: local on-profile: local
import: import:
- "nacos:${spring.application.name}.yml?group=DEFAULT_GROUP" - "nacos:${spring.application.name}.yml?group=DEFAULT_GROUP"
- "nacos:linkwe-common.yml?group=DEFAULT_GROUP" - "nacos:bs-common.yml?group=DEFAULT_GROUP"
main: main:
allow-bean-definition-overriding: true allow-bean-definition-overriding: true
allow-circular-references: true allow-circular-references: true
...@@ -15,9 +19,14 @@ spring: ...@@ -15,9 +19,14 @@ spring:
# 配置中心 # 配置中心
config: config:
# 命名空间id(此处不用public,因public初始化的空间, id为空) 4e237601-cea8-414d-b7b9-d7adc8cbcf95 # 命名空间id(此处不用public,因public初始化的空间, id为空) 4e237601-cea8-414d-b7b9-d7adc8cbcf95
namespace: 090c1f23-5f64-4b92-acd3-a6bda38219aa # 预发布
# namespace: a9bf07e4-4a9a-4d6f-ab9f-a708d1c5e892
# 测试
namespace: d659c242-b7ce-473b-bb87-05be5982bad5
# nacos的ip地址和端口 120.79.64.17:10848 # nacos的ip地址和端口 120.79.64.17:10848
server-addr: 192.168.3.102:8848 # server-addr: 192.168.5.4:8848
# 测试
server-addr: 192.168.3.102:8868
# 这个就表示 在我们nacos命名空间id为 dev中 有一个data-id 为 demo-service.yml 的配置文件 读取这个里面的配置 # 这个就表示 在我们nacos命名空间id为 dev中 有一个data-id 为 demo-service.yml 的配置文件 读取这个里面的配置
file-extension: yml file-extension: yml
config-retry-time: 300000 config-retry-time: 300000
...@@ -34,7 +43,7 @@ spring: ...@@ -34,7 +43,7 @@ spring:
on-profile: dev on-profile: dev
import: import:
- "nacos:${spring.application.name}.yml?group=DEFAULT_GROUP" - "nacos:${spring.application.name}.yml?group=DEFAULT_GROUP"
- "nacos:linkwe-common.yml?group=DEFAULT_GROUP" - "nacos:bs-common.yml?group=DEFAULT_GROUP"
main: main:
allow-bean-definition-overriding: true allow-bean-definition-overriding: true
allow-circular-references: true allow-circular-references: true
...@@ -45,9 +54,9 @@ spring: ...@@ -45,9 +54,9 @@ spring:
# 配置中心 # 配置中心
config: config:
# 命名空间id(此处不用public,因public初始化的空间, id为空) # 命名空间id(此处不用public,因public初始化的空间, id为空)
namespace: 090c1f23-5f64-4b92-acd3-a6bda38219aa namespace: 3020f836-3dde-46e9-b347-44167a409f7e
# nacos的ip地址和端口 # nacos的ip地址和端口
server-addr: 192.168.3.102:8848 server-addr: nacos3.release.glsx.com:8838
# 这个就表示 在我们nacos命名空间id为 dev中 有一个data-id 为 demo-service.yml 的配置文件 读取这个里面的配置 # 这个就表示 在我们nacos命名空间id为 dev中 有一个data-id 为 demo-service.yml 的配置文件 读取这个里面的配置
file-extension: yml file-extension: yml
config-retry-time: 300000 config-retry-time: 300000
...@@ -65,7 +74,7 @@ spring: ...@@ -65,7 +74,7 @@ spring:
on-profile: test on-profile: test
import: import:
- "nacos:${spring.application.name}.yml?group=DEFAULT_GROUP" - "nacos:${spring.application.name}.yml?group=DEFAULT_GROUP"
- "nacos:linkwe-common.yml?group=DEFAULT_GROUP" - "nacos:bs-common.yml?group=DEFAULT_GROUP"
main: main:
allow-bean-definition-overriding: true allow-bean-definition-overriding: true
allow-circular-references: true allow-circular-references: true
...@@ -78,7 +87,7 @@ spring: ...@@ -78,7 +87,7 @@ spring:
# 命名空间id(此处不用public,因public初始化的空间, id为空) # 命名空间id(此处不用public,因public初始化的空间, id为空)
namespace: 3020f836-3dde-46e9-b347-44167a409f7e namespace: 3020f836-3dde-46e9-b347-44167a409f7e
# nacos的ip地址和端口 # nacos的ip地址和端口
server-addr: nacos3.test.glsx.com:8848 server-addr: 192.168.2.11:8848
# 这个就表示 在我们nacos命名空间id为 dev中 有一个data-id 为 demo-service.yml 的配置文件 读取这个里面的配置 # 这个就表示 在我们nacos命名空间id为 dev中 有一个data-id 为 demo-service.yml 的配置文件 读取这个里面的配置
file-extension: yml file-extension: yml
config-retry-time: 300000 config-retry-time: 300000
...@@ -96,7 +105,7 @@ spring: ...@@ -96,7 +105,7 @@ spring:
on-profile: beta on-profile: beta
import: import:
- "nacos:${spring.application.name}.yml?group=DEFAULT_GROUP" - "nacos:${spring.application.name}.yml?group=DEFAULT_GROUP"
- "nacos:linkwe-common.yml?group=DEFAULT_GROUP" - "nacos:bs-common.yml?group=DEFAULT_GROUP"
main: main:
allow-bean-definition-overriding: true allow-bean-definition-overriding: true
allow-circular-references: true allow-circular-references: true
...@@ -109,7 +118,7 @@ spring: ...@@ -109,7 +118,7 @@ spring:
# 命名空间id(此处不用public,因public初始化的空间, id为空) # 命名空间id(此处不用public,因public初始化的空间, id为空)
namespace: ae6c55f2-2313-4a21-b935-6dc478ea9c7b namespace: ae6c55f2-2313-4a21-b935-6dc478ea9c7b
# nacos的ip地址和端口 # nacos的ip地址和端口
server-addr: nacos3.beta.glsx.com:8848 server-addr: 192.168.5.4:8848
# 这个就表示 在我们nacos命名空间id为 dev中 有一个data-id 为 demo-service.yml 的配置文件 读取这个里面的配置 # 这个就表示 在我们nacos命名空间id为 dev中 有一个data-id 为 demo-service.yml 的配置文件 读取这个里面的配置
file-extension: yml file-extension: yml
config-retry-time: 300000 config-retry-time: 300000
...@@ -127,26 +136,26 @@ spring: ...@@ -127,26 +136,26 @@ spring:
on-profile: release on-profile: release
import: import:
- "nacos:${spring.application.name}.yml?group=DEFAULT_GROUP" - "nacos:${spring.application.name}.yml?group=DEFAULT_GROUP"
- "nacos:linkwe-common.yml?group=DEFAULT_GROUP" - "nacos:bs-common.yml?group=DEFAULT_GROUP"
main: main:
allow-bean-definition-overriding: true allow-bean-definition-overriding: true
allow-circular-references: true allow-circular-references: true
cloud: cloud:
nacos: nacos:
username: nacos username: nacos
password: Glsx@260422 password: nacos
# 配置中心 # 配置中心
config: config:
# 命名空间id # 命名空间id(此处不用public,因public初始化的空间, id为空)
# namespace: public namespace: a7b2e44c-1856-4344-98dc-c1065648c840
# nacos的ip地址和端口 # nacos的ip地址和端口
server-addr: 192.168.3.63:8848 server-addr: nacos3.release.glsx.com:8838
# 这个就表示 在我们nacos命名空间id为 dev中 有一个data-id 为 demo-service.yml 的配置文件 读取这个里面的配置 # 这个就表示 在我们nacos命名空间id为 dev中 有一个data-id 为 demo-service.yml 的配置文件 读取这个里面的配置
file-extension: yml file-extension: yml
config-retry-time: 300000 config-retry-time: 300000
# 发布到注册中心 (如果没有使用可以不配) # 发布到注册中心 (如果没有使用可以不配)
discovery: discovery:
# 命名空间id # 命名空间id(此处不用public,因public初始化的空间, id为空)
# namespace: ${spring.cloud.nacos.config.namespace} namespace: ${spring.cloud.nacos.config.namespace}
# nacos的ip地址和端口 # nacos的ip地址和端口
server-addr: ${spring.cloud.nacos.config.server-addr}
\ No newline at end of file \ No newline at end of file
server-addr: ${spring.cloud.nacos.config.server-addr}
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
<select id="getCarBrandInfo" resultMap="BaseResultMap"> <select id="getCarBrandInfo" resultMap="BaseResultMap">
SELECT SELECT
<include refid="Base_Column_List"/> <include refid="Base_Column_List"/>
FROM platform_carbrand FROM bs_carbrand
WHERE parent_id > 0 WHERE parent_id > 0
<if test="autohomeId != null and autohomeId != ''"> <if test="autohomeId != null and autohomeId != ''">
AND autohome_id = #{autohomeId} AND autohome_id = #{autohomeId}
...@@ -44,7 +44,7 @@ ...@@ -44,7 +44,7 @@
<select id="getCarBrandForParent" resultMap="BaseResultMap"> <select id="getCarBrandForParent" resultMap="BaseResultMap">
SELECT SELECT
<include refid="Base_Column_List"/> <include refid="Base_Column_List"/>
FROM platform_carbrand FROM bs_carbrand
WHERE parent_id = -2 WHERE parent_id = -2
AND autohome_id = #{autohomeId} AND autohome_id = #{autohomeId}
AND is_used = 0 AND is_used = 0
...@@ -58,9 +58,9 @@ ...@@ -58,9 +58,9 @@
chb.brand AS childName, chb.bid AS childId, chb.bra_letter as childLetter, chb.brand AS childName, chb.bid AS childId, chb.bra_letter as childLetter,
pcs.carseries, pcs.csid, pcs.series_letter pcs.carseries, pcs.csid, pcs.series_letter
FROM FROM
platform_carbrand AS chb bs_carbrand AS chb
INNER JOIN INNER JOIN
platform_carbrand AS pb ON chb.parent_id = pb.bid and pb.is_used = 0 bs_carbrand AS pb ON chb.parent_id = pb.bid and pb.is_used = 0
LEFT JOIN LEFT JOIN
platform_carseries AS pcs ON chb.bid = pcs.brand_id and pcs.is_used = 0 platform_carseries AS pcs ON chb.bid = pcs.brand_id and pcs.is_used = 0
WHERE WHERE
......
...@@ -36,7 +36,7 @@ ...@@ -36,7 +36,7 @@
<select id="getCarSeriesInfo" resultMap="BaseResultMap"> <select id="getCarSeriesInfo" resultMap="BaseResultMap">
SELECT SELECT
<include refid="Base_Column_List"/> <include refid="Base_Column_List"/>
FROM platform_carseries FROM bs_carseries
WHERE autohome_id = #{autohomeId} WHERE autohome_id = #{autohomeId}
LIMIT 1 LIMIT 1
</select> </select>
......
...@@ -52,7 +52,7 @@ ...@@ -52,7 +52,7 @@
<select id="getCarTypeInfo" resultMap="BaseResultMap"> <select id="getCarTypeInfo" resultMap="BaseResultMap">
SELECT SELECT
<include refid="Base_Column_List"/> <include refid="Base_Column_List"/>
FROM platform_cartype FROM bs_cartype
WHERE car_series_id = #{carSeriesId} WHERE car_series_id = #{carSeriesId}
AND autohome_id = #{autohomeId} AND autohome_id = #{autohomeId}
LIMIT 1 LIMIT 1
...@@ -61,7 +61,7 @@ ...@@ -61,7 +61,7 @@
<!-- 通过车系ID查询车系下的车型列表 --> <!-- 通过车系ID查询车系下的车型列表 -->
<select id="getCarTypeListBySeriesId" resultMap="CarTypeDtoResultMap"> <select id="getCarTypeListBySeriesId" resultMap="CarTypeDtoResultMap">
SELECT id, car_type_name, identifying_photo SELECT id, car_type_name, identifying_photo
FROM platform_cartype FROM bs_cartype
WHERE car_series_id = #{carSeriesId} WHERE car_series_id = #{carSeriesId}
AND status = 0 AND status = 0
</select> </select>
......
package com.bs.cardata.controller;
import com.bs.cardata.BsApplication;
import com.bs.cardata.constant.ServiceConstants;
import com.bs.common.core.redis.RedisService;
import com.bs.common.utils.sign.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import java.util.UUID;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* CarDataApiController clearCache 接口测试
*/
@Slf4j
@SpringBootTest(classes = BsApplication.class, properties = "spring.application.name=bs-car-data")
@AutoConfigureMockMvc
@ActiveProfiles("local")
public class CarDataApiControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private RedisService redisService;
/**
* 生成合法加密参数
*/
private String[] generateValidParams() {
String nonce = UUID.randomUUID().toString();
String timestamp = String.valueOf(System.currentTimeMillis());
String plainText = nonce + timestamp + ServiceConstants.CLEAR_CACHE_SECRET;
String token = Md5Utils.getMD532Str(plainText);
return new String[]{token, timestamp, nonce};
}
/**
* 测试正常清除缓存
*/
@Test
public void testClearCache_success() throws Exception {
String[] params = generateValidParams();
mockMvc.perform(get("/common/api/clearCache")
.param("token", params[0])
.param("timestamp", params[1])
.param("nonce", params[2]))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(200))
.andExpect(jsonPath("$.msg").value("缓存清除成功"));
log.info("testClearCache_success 通过");
}
/**
* 测试时间戳格式错误
*/
@Test
public void testClearCache_invalidTimestamp() throws Exception {
String nonce = UUID.randomUUID().toString();
String token = Md5Utils.getMD532Str(nonce + "abc" + ServiceConstants.CLEAR_CACHE_SECRET);
mockMvc.perform(get("/common/api/clearCache")
.param("token", token)
.param("timestamp", "abc")
.param("nonce", nonce))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.msg").value("时间戳格式不正确"));
log.info("testClearCache_invalidTimestamp 通过");
}
/**
* 测试时间戳过期(超出5分钟窗口)
*/
@Test
public void testClearCache_expiredTimestamp() throws Exception {
String nonce = UUID.randomUUID().toString();
// 构造一个6分钟前的时间戳
String timestamp = String.valueOf(System.currentTimeMillis() - 6 * 60 * 1000L);
String plainText = nonce + timestamp + ServiceConstants.CLEAR_CACHE_SECRET;
String token = Md5Utils.getMD532Str(plainText);
mockMvc.perform(get("/common/api/clearCache")
.param("token", token)
.param("timestamp", timestamp)
.param("nonce", nonce))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.msg").value("请求已过期,时间戳超出有效窗口"));
log.info("testClearCache_expiredTimestamp 通过");
}
/**
* 测试签名校验失败(错误的token)
*/
@Test
public void testClearCache_invalidToken() throws Exception {
String nonce = UUID.randomUUID().toString();
String timestamp = String.valueOf(System.currentTimeMillis());
mockMvc.perform(get("/common/api/clearCache")
.param("token", "invalid_token_123456")
.param("timestamp", timestamp)
.param("nonce", nonce))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.msg").value("加密参数校验失败"));
log.info("testClearCache_invalidToken 通过");
}
/**
* 测试加密参数只能使用一次(重放攻击)
*/
@Test
public void testClearCache_nonceReuse() throws Exception {
String[] params = generateValidParams();
// 第一次调用:应成功
mockMvc.perform(get("/common/api/clearCache")
.param("token", params[0])
.param("timestamp", params[1])
.param("nonce", params[2]))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(200));
// 第二次使用相同参数:应被拒绝
mockMvc.perform(get("/common/api/clearCache")
.param("token", params[0])
.param("timestamp", params[1])
.param("nonce", params[2]))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.msg").value("该加密参数已被使用,请重新生成"));
log.info("testClearCache_nonceReuse 通过");
}
/**
* 测试缺少必要参数
*/
@Test
public void testClearCache_missingParams() throws Exception {
mockMvc.perform(get("/common/api/clearCache"))
.andDo(print())
.andExpect(status().isBadRequest());
log.info("testClearCache_missingParams 通过");
}
}
...@@ -10,8 +10,8 @@ import org.springframework.test.context.ActiveProfiles; ...@@ -10,8 +10,8 @@ import org.springframework.test.context.ActiveProfiles;
import java.util.List; import java.util.List;
@Slf4j @Slf4j
@SpringBootTest(properties = "spring.application.name=linkwe-car-data") @SpringBootTest(properties = "spring.application.name=bs-car-data")
@ActiveProfiles("test")//测试环境 @ActiveProfiles("local")//测试环境
public class CarDataServiceTest { public class CarDataServiceTest {
@Autowired @Autowired
...@@ -22,7 +22,7 @@ public class CarDataServiceTest { ...@@ -22,7 +22,7 @@ public class CarDataServiceTest {
@Test @Test
public void testSyncCarInfo() { public void testSyncCarInfo() {
String baseUrl = "http://www.autohome.com.cn/grade/carhtml/C.html"; String baseUrl = "https://www.autohome.com.cn/web-main/car/web/price/treeMenu?extendseries=1";
carDataService.syncCarInfo(baseUrl); carDataService.syncCarInfo(baseUrl);
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!