美文网首页Java
Alibaba 服务调用

Alibaba 服务调用

作者: TZX_0710 | 来源:发表于2020-09-01 17:07 被阅读0次

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

开发一个服务接口地

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

    @RestController
    public class ConsumerController {
        @GetMapping("/hello")
        public String hello() {
            return "hello World";
        }
    }
}

消费者调用

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;
    }

}
nacos服务调用

第二种方式采用Feign调用 可以参考作者前面写过的SpringCloud Feign调用


项目示例代码结构

相关文章

网友评论

    本文标题:Alibaba 服务调用

    本文链接:https://www.haomeiwen.com/subject/zsmvsktx.html