SpringCloud : 两个微服务进程之间通信(远程调用)

SpringCloud : 两个微服务进程之间通信(远程调用)_第1张图片

1.     加依赖(依赖tcloud-user-provider)



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0modelVersion>

 

   <groupId> com.svw.tbox.tcloud.user groupId>

   <artifactId>tcloud-user-consumerartifactId>

   <version>0.0.1-SNAPSHOTversion>

   <name>tcloud-user-consumername>

   <url>http://maven.apache.orgurl>

 

   <dependencies>

      <dependency>

          <groupId>com.pateo.cloudgroupId>

          <artifactId>tcloud-user-providerartifactId>

          <version>0.0.1-SNAPSHOTversion>

      dependency>

   dependencies>

project>

1.     启动类中声明RestTemplate


packagecom.svw.tbox.tcloud.user.consumer;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.Bean;

import org.springframework.web.client.RestTemplate;

 

@SpringBootApplication

publicclass ConsumerApplication {

   @Bean

   public RestTemplate restTemplate(){

      returnnew RestTemplate();

   }

   publicstaticvoid main(String[] args) {

      SpringApplication.run(ConsumerApplication.class, args);

   }

}

1.    配置微服务端口


tcloud-user-provider端口配置为8000

tcloud-user-provider\src\main\resources\

中添加文件application.properties ,内容配置端口

server.port = 8000

 

或者在application.yml中添加

server:

  port: 9000

tcloud-user-consumer端口配置为9000

tcloud-user-consumer\src\main\resources\application.properties 中添加

server.port = 9000

 

或者在application.yml中添加

server:

  port: 9000

 

1.     Controller中远程调用



packagecom.svw.tbox.tcloud.user.consumer.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.client.RestTemplate;

importcom.svw.tbox.tcloud.user.consumer.entity.User;

 

@RestController

publicclass TboxController {

   @Autowired

   private RestTemplate restTemplate;

  

   @GetMapping("/user/{name}")

   public List likeName(@PathVariable String name){

      returnthis.restTemplate.getForObject("http://localhost:8000/likeName/"+name, List.class) ;

   }

}

效果

1.     启动tcloud-user-provider

 

2.     启动tcloud-user-consumer

 

调用过程如下:

访问http://localhost:9000/user/hrf

 SpringCloud : 两个微服务进程之间通信(远程调用)_第2张图片

 

 SpringCloud : 两个微服务进程之间通信(远程调用)_第3张图片

 


效果:


你可能感兴趣的:(spring,cloud)