这篇文章主要介绍“SpringCloud服务的发现与调用实例分析”,在日常操作中,相信很多人在SpringCloud服务的发现与调用实例分析问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”SpringCloud服务的发现与调用实例分析”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
一、服务提供者
<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;
}
}启动验证一下,可以正常返回。

二、服务消费者
@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;
}
}启动验证一下

可以看到,我们调用8003消费者服务,消费者服务又调用了8002服务提供者的接口,并正确返回了结果。
到此,关于“SpringCloud服务的发现与调用实例分析”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注天达云网站,小编会继续努力为大家带来更多实用的文章!