SpringCloud之Nacos服务发现(十六)

一 服务提供配置

  • pom.xml

 
        org.springframework.boot
        spring-boot-starter-web
    
    
    
        org.springframework.cloud
        spring-cloud-starter-alibaba-nacos-discovery
        0.9.0.RELEASE
    

 

  • application.yml

    server:
      port: 8881
    spring:
      application:
        name: nacos-product
      cloud:
        nacos:
          discovery:
            server-addr: 192.168.180.113:8848

     

  • 启动类

    @SpringBootApplication
    @EnableDiscoveryClient
    public class NacosProductApplication {
    ​
        public static void main(String[] args) {
            SpringApplication.run(NacosProductApplication.class, args);
        }
    ​
    }
     
  • web层

     1 /**
     2  * @author WGR
     3  * @create 2019/10/25 -- 0:29
     4  */
     5 @RestController
     6 @RequestMapping("/user")
     7 public class UserController {
     8     @GetMapping
     9     public String getUser(){
    10         return "admin";
    11     }
    12 }

     

测试结果:

SpringCloud之Nacos服务发现(十六)_第1张图片

二 提供消费配置

  • pom.xml

    
                org.springframework.cloud
                spring-cloud-starter-openfeign
            
            
            
                org.springframework.boot
                spring-boot-starter-web
            
            
                org.springframework.cloud
                spring-cloud-starter-alibaba-nacos-discovery
                0.9.0.RELEASE
            
            
                org.springframework.boot
                spring-boot-starter-test
                test
                
                    
                        org.junit.vintage
                        junit-vintage-engine
                    
                
            
        

     

  • application.yml

    server:
      port: 8882
    spring:
      application:
        name: nacos-consumer
      cloud:
        nacos:
          discovery:
            server-addr: 192.168.180.113:8848

     

  • 启动类配置

    @SpringBootApplication
    @EnableFeignClients
    public class NacosConsumerApplication {
    ​
        public static void main(String[] args) {
            SpringApplication.run(NacosConsumerApplication.class, args);
        }
    ​
    }
    ​

     

  • web层

    /**
     * @author WGR
     * @create 2019/10/25 -- 0:46
     */
    @RestController
    @RequestMapping("/test")
    public class TestController {
    ​
        @Autowired(required = false)
        private TestService testService;
    ​
        @GetMapping("/user")
        public String getUser() {
            return testService.getUser();
        }
    }

     

  • service层

    /**
     * @author WGR
     * @create 2019/10/25 -- 0:47
     */
    @FeignClient("nacos-product")
    public interface TestService {
    ​
        @GetMapping("user")
        String getUser();
    ​
    }

    测试:http://localhost:8882/test/user

 

你可能感兴趣的:(SpringCloud之Nacos服务发现(十六))