一起艳学天气微服务(三)——微服务的消费
服务还能被使用,被消费。目前消费者框架主要有HttpClient,Ribbon,Feign等。
现在我们先使用Feign演示给大家看。
1、启动Fegin
在application类上加@EnableFeignClients
2、定义Fegin客户端
@FeignClient("yh-weather1-eureka-client")
public interface CityClient {
@RequestMapping(value="/weather/getCity", method=RequestMethod.GET)
Result listCity() throws Exception;
}
3、修改城市列表服务
public Result getCity(String json) {
return this.doGetWeatherData(json).getResult();
}
private CityResponse doGetWeatherData(String json) {
CityResponse weather = new CityResponse();
try {
Result r = new Result();
r.setMsg(json);
weather.setResult(r);
// weather = (CityResponse) _jsonUtil.json2Bean(json, CityResponse.class);
} catch (Exception e) {
throw new RuntimeException("天气信息解析失败");
}
return weather;
}
4、修改控制层
@GetMapping("/cityName/{cityName}")
@ResponseBody
public Map<String,Object> getReportByCityId(@PathVariable("cityName") String cityName, Model model) throws Exception {
// 由城市数据API微服务来提供数据
Result cityList = null;
try {
// 调用城市数据API
cityList = cityClient.listCity();
} catch (Exception e) {
throw new RuntimeException("获取城市信息异常!", e);
}
Map<String,Object> map = new HashMap<String, Object>();
map.put("cityId", cityName);
map.put("cityList", cityList);
Result r = scenicDataService2.getDataByCityId(cityName);
map.put("report", r.getCity());
return map;
}
5、配置类
spring.application.name: yh-weather-eureka-report
eureka.client.serviceUrl.defaultZone: http://localhost:8761/eureka/
feign.client.config.feignName.connectTimeout: 5000
feign.client.config.feignName.readTimeout: 5000
hystrix.command.default.execution.timeout.enabled: false
这里有两个需要注意的,第一hystrix.command.default.execution.timeout.enabled: false,这个要关闭,不知道为什么调用后就超时了。
第二用GetMapping注解,报错提示没有get,post。
还有一点是clent的uri要和controller对应,且返回类型需一致。
这里没有测试开多个端口,看能不能实现负载均衡,开多个由于内存,提示内存过少。
我们将会以系统分层、服务测试、服务拆分、服务通信、服务注册、服务发现、服务消费、集中配置、日志管理、容器部署、安全防护、自动扩展等方面介绍微服务。源码下载地址:http://47.98.237.162/detail/1/167