SpringCloud服务的发现与调用实例分析

这篇文章主要介绍“SpringCloud服务的发现与调用实例分析”,在日常操作中,相信很多人在SpringCloud服务的发现与调用实例分析问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”SpringCloud服务的发现与调用实例分析”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

一、服务提供者

  • 新建Maven项目provider

  • 引入项目依赖

    <parent>
        <groupId>com.cxy965</groupId>
        <artifactId>parent</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../parent/pom.xml</relativePath>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

新建配置文件application.yml

server:
  port: 8002
spring:
  application:
    name: provider
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8001/eureka/
    fetch-registry: true

创建启动类和服务接口,为了简便,暂时将服务接口放在了启动类,实际项目中,最好还是要放在controller中。

@EnableEurekaClient
@SpringBootApplication
@RestController
public class ProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class, args);
    }
    @GetMapping("/hello")
    public String hello(String name) {
       return "Hello "+name;
    }
}

启动验证一下,可以正常返回。

二、服务消费者

  • 参考provider项目创建consumer项目

  • 修改配置文件中的端口和应用名称为8003、consumer

  • 创建启动类和服务消费代码

@EnableEurekaClient
@SpringBootApplication
@RestController
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    RestTemplate restTemplate;
    @GetMapping("/hello")
    public String hello(String name) {
        List<ServiceInstance> list = discoveryClient.getInstances("provider");
        ServiceInstance instance = list.get(0);
        String host = instance.getHost();
        int port = instance.getPort();
        String returnInfo = restTemplate.getForObject("http://" + host + ":" + port + "/hello?name={1}", String.class, name);
        return returnInfo;
    }
}

启动验证一下

SpringCloud服务的发现与调用实例分析  springcloud 第1张

可以看到,我们调用8003消费者服务,消费者服务又调用了8002服务提供者的接口,并正确返回了结果。

到此,关于“SpringCloud服务的发现与调用实例分析”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注蜗牛博客网站,小编会继续努力为大家带来更多实用的文章!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接