SpirngCloud中服务间2种restful调用方式
- RestTemplate
- Feign
描述现有wechatTask-guns中已经有helloWorld服务getToken服务
helloWorld访问无需带参数
http://127.0.0.1:8089//wechatTask//study/helloWorld
返回数据格式

getToken访问地址是(Post方式通过api)
http://localhost:8089/wechatTask/api/getToken?username=867463020550111&password=aaa6a6f01e519ea0253b7e884b3ae783a&type=10&clientType=10
getToken返回数据结构

{
"code": 200,
"data": {
"agent_id": "",
"client_Type": "10",
"created_at": "2019-09-01 18:22:54",
"expiry_time": "2019-09-01 18:22:54",
"sub_user_id": "",
"token": "a0adeebff3fe24964d184b7546460abb",
"type": "",
"user_id": ""
},
"eventType": 0,
"msg": "OK",
"oK": true,
"seqId": 0,
"time": 1567333374413
}
在msgSns模块创建HelloworldTemolateClientController(模拟RestTemolate的3种使用方式)
/**
* 主要用于模拟RestTemolate的3种使用方式
*
*/
@Controller
@RequestMapping()
public class HelloworldTemolateClientController {
Logger logger = LoggerFactory.getLogger(HelloworldTemolateClientController.class);
@GetMapping("/helloworldRestTemplate")
@ResponseBody
//第一种情况(直接使用restTemolate,url写死
public String helloWorldrestTemplate(){
RestTemplate restTemplate = new RestTemplate();
//第二个参数是放回类型
String response = restTemplate.getForObject("http://127.0.0.1:8089//wechatTask//study/helloWorld",String.class);
logger.info("响应的数据response= {}",response);
return response;
}
@Autowired
private LoadBalancerClient loadBalancerClient; //SpringCloud确认服务的方式
@GetMapping("/helloworldRestTemplate2")
@ResponseBody
//第2 种情况(通过LoadBalancerClient获取应用名urld的host 和post,然后再使用restTemplate)
public String helloWorldRestTemplate2(){
//其中WECHAT_TASK就是wechatTask-guns注册在Eureka的名字;利用名字获取多个服务中的host和端口,并组合成url
ServiceInstance serviceInstance = loadBalancerClient.choose("wechat-task");
String url = String.format("http://%s:%s",serviceInstance.getHost(),serviceInstance.getPort())
+"wechatTask/study/helloWorld";
RestTemplate restTemplate = new RestTemplate();
//第二个参数是放回类型
String response = restTemplate.getForObject(url,String.class);
logger.info("响应的数据response= {}",response);
return response;
}
@Autowired
private RestTemplate restTemplate2;
@GetMapping("/helloworldRestTemplate3")
@ResponseBody
//第3种情况(利用@LoadBalanced,可在restTemplate里使用应用名字)
public String helloWorldRestTemplate3(){
//第二个参数是放回类型
//String response = restTemplate2.getForObject("http://WECHAT_TASK/wechatTask/study/helloWorld",String.class);//这样会报错,主要是使用了下划线,后来改为中线即可
String response = restTemplate2.getForObject("http://wechat-task/wechatTask/study/helloWorld",String.class);//这样会报错
logger.info("响应的数据response= {}",response);
return response;
}
}
特别说明原来wechatTask-guns注册名字为wechat-task(不允许用下划线)
#不允许用下划线,否则会报这个错误
java.lang.IllegalStateException: Request URI does not contain a valid hostname

解决参考:
java.lang.IllegalStateException: Request URI does not contain a valid hostname
运行并测试
http://localhost:8080//helloworldRestTemplate
http://localhost:8080//helloworldRestTemplate2
http://localhost:8080//helloworldRestTemplate3
网友评论