最近有一个springcloud的feign请求,用于获取坐标经纬度的信息,返回结果永远是固定不变的,所以考虑优化一下,不然每次转换几个坐标都要去请求feign,返回的所有坐标信息,数据量太大导致耗时大,重复性请求。
第一步:创建配置类,用于在springboot项目启动后就执行feign接口用于查询所有的经纬度信息【返回结果封装在了一个map集合】。
@Component
@Order(value = 1)//定义组件加载顺序
@Slf4j
public class GetLatLonConfig implements ApplicationRunner {
@Autowired
private BaseStorageFeignService baseStorageFeignService;
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("=========== 项目启动后,开始执行查询经纬度坐标 的方法 =============");
//查询经纬度
ResponseWrapper<Map<String, Location>> all = baseStorageFeignService.all();
Map<String, Location> tempLocationMap = all.getObj();
if(tempLocationMap == null) {
log.error("====== 项目启动后,执行查询经纬度坐标方法的结果:获取坐标经纬度信息为空");
throw new RuntimeException("获取坐标经纬度信息为空");
}
}
}
第二部: 配置类,用于控制feign接口请求一次之后,如果在调用这个feign接口,就不再真正发送请求,因为第一次请求feign的结果已经封装在了本地的静态变量中。
@Aspect
@Configuration
@Slf4j
public class LocationConfig {
private static Map<String, Location> all = null;
@Pointcut("execution(public * xxxxxx(..))")//xxxxxx 替换为 feign方法所在的全限定性路径名称
public void executeAll() {
}
@Around("executeAll()")
public Object location(ProceedingJoinPoint jp) {
if (all != null) {
return new ResponseWrapper(all);
}
try {
ResponseWrapper<Map<String, Location>> result = (ResponseWrapper<Map<String, Location>>) jp.proceed();
all = result.getObj();
} catch (Throwable throwable) {
log.error("Error.", throwable);
}
return new ResponseWrapper(all);
}
}
当代码中再次调用feign方法时,就不会真正去走微服务feign调用,降低程序运行时间。