1. 调用服务的方式有多种这边只展示采用restTemplate方式调用

开发一个服务接口地

  1. package com.example;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. @EnableDiscoveryClient //注册
  8. @SpringBootApplication
  9. public class HelloWorldApplication {
  10. public static void main(String[] args) {
  11. SpringApplication.run( HelloWorldApplication.class, args );
  12. }
  13. @RestController
  14. public class ConsumerController {
  15. @GetMapping("/hello")
  16. public String hello() {
  17. return "hello World";
  18. }
  19. }
  20. }

消费者调用

package base;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient//注册
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run( ConsumerApplication.class, args );
    }

}

@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consumer")
    public String consumer() {
        //调用服务
        // 通过服务名获取到注册到nacos 的ip+端口地址信息(集群会获取多个)
        // rpc 调用
        String result = restTemplate.getForObject( "http://server-provider/hello", String.class );
        System.out.println( "调用alibaba-server服务,result:" + result );
        return result;
    }

}

Alibaba-服务调用 - 图1

第二种方式采用Feign调用 可以参考作者前面写过的SpringCloud Feign调用
Alibaba-服务调用 - 图2