码迷,mamicode.com
首页 > 编程语言 > 详细

31. Springboot中使用RestTemplate

时间:2017-08-09 16:53:48      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:springboot

一. 前言

官网使用说明

获取Eureka实例

public String serviceUrl() {
    InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
    return instance.getHomePageUrl();
}


步骤:


二. 导入包

pom.xml

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>


三. 修改启动Application

@EnableCircuitBreaker
@EnableDiscoveryClient
public class HellloMain {
	
	@Bean
	@LoadBalanced
	RestTemplate restTemplate() {
		return new RestTemplate();
	}
	
	public static void main(String[] args) {
		SpringApplication.run(HelloMain.class, args);

	}
	
}


四. 业务使用

private int xxxx(String body) {
	RestTemplate restTemplate = new RestTemplate();
	HttpHeaders headers = new HttpHeaders();
	MediaType type = MediaType.parseMediaType("application/json");
	headers.setContentType(type);
		
	HttpEntity<String> formEntity = new HttpEntity<String>(body, headers);
		
	String result = restTemplate.postForObject(getEurkaClient("hello-module"), 
				formEntity,
				String.class);
	return 0;
}
public String getEurkaClient(String end) {
        InstanceInfo instance = discoveryClient.getNextServerFromEureka("smarthome-phihome", false);
	return instance.getHomePageUrl() + end;
}


这样就可以在应用程序之间互相调用


本文出自 “www.bogo.com” 博客,请务必保留此出处http://483181.blog.51cto.com/473181/1954798

31. Springboot中使用RestTemplate

标签:springboot

原文地址:http://483181.blog.51cto.com/473181/1954798

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!