1. 程式人生 > >31. Springboot中使用RestTemplate

31. Springboot中使用RestTemplate

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