采用RestTemplate方式调用:
(1)添加RestTemplate到Spring容器中:
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* Created by lj on 2020/4/26.
*/
@Configuration
public class RestConfiguration {
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
(2)使用:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.Random;
/**
* Created by lj on 2020/4/25.
*/
@RestController
@RequestMapping(value = "/User",produces = "application/json;charest=UTF-8")
public class UserController {
@Autowired
private RestTemplate restTemplate;
@RequestMapping(value = "/getUserInfo/{id}")
public String getUserInfo(@PathVariable("id") Integer id){
return id+":用户信息返回成功";
}
@RequestMapping(value = "/getOrderByID/{id}")
public String getOrderByID(@PathVariable("id") Integer id){
Random random = new Random();
//com-eureka-client001为spring的服务名
String result = restTemplate.getForObject("http://com-eureka-client001/Order/getOrderInfo/"+random.nextInt(100),String.class);
//String result = restTemplate.getForObject("http://127.0.0.1:8088/Order/getOrderInfo/"+random.nextInt(100),String.class);
return result;
}
}