RestTemplate更优雅调用RESTful服务的方式

1、服务提供者将服务注册到Eureka上,服务名为:CLOUD-PAYMENT-SERVICE

RestTemplate更优雅调用RESTful服务的方式_第1张图片

 2、服务提供者CLOUD-PAYMENT-SERVICE提供如下方法:

@RestController
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentServiceImpl paymentService;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment){

        int result = paymentService.create(payment);
        System.out.println("***" + result);

        if(result > 0){
            return new CommonResult(200, "插入数据库成功, serverPort = " + serverPort, result);
        }else {
            return new CommonResult(444, "插入数据哭失败", null);
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){

        Payment payment = paymentService.getPaymentById(id);
        System.out.println("***" + payment);

        if(payment != null){
            return new CommonResult(200, "查询成功, serverPort = " + serverPort, payment);
        }else {
            return new CommonResult(444, "没有对应记录,查询ID:" + id, null);
        }
    }

}

3、服务消费者注册Eureka,并消费对应服务

1、增加配置类

@Configuration
public class ApplicationContextConfig {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

2、通过RestTemplate的restTemplate.postForObject方法进行服务消费

是对getForEntity进一步封装,该方法会将信息封装成对应的bean

@RestController
@Slf4j
public class OrderController {

    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE/";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping(value = "consumer/payment/create")
    public CommonResult create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"payment/create", payment, CommonResult.class);
    }

    @GetMapping(value = "consumer/payment/get/{id}")
    public CommonResult getPayment(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL+"payment/get/"+id, CommonResult.class);
    }
}

3、启动Eureka、启动8001服务提供者、启动80服务消费者

可以看到,通过http://localhost/consumer/payment/get/1就能访问8001提供的服务。

4、RestTemplate提供@LoadBalanced注解,如果有多个名称相同的服务端,则会提供负载均衡能力 

再来一个8002,服务提供与8001相同:

RestTemplate更优雅调用RESTful服务的方式_第2张图片

然后我们再次查看服务情况:

点击第一次:

RestTemplate更优雅调用RESTful服务的方式_第3张图片

点击第二次:

可以看到,这次使用到了8002提供的服务,默认采用的轮询使用服务的方式。

你可能感兴趣的:(springcloud)