上一篇搭建的是eureka服务提供者,当然要有消费者。话不多说,上代码
1.新建eureka-consumer模块,pom文件如下
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.feng</groupId>
<artifactId>cloud-study</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>eureka-consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>eureka-consumer</name>
<description>cloud study for two month</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.application.yml文件添加配置
spring:
application:
name: eureka-consumer
server:
port: 8803
servlet:
context-path: /consumer
eureka:
instance:
instanceId: ${spring.application.name}:${vcap.application.instance-id:${spring.application.instance-id:${random.value}}}
hostname: localhost
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://localhost:8801/register/eureka/
3.编写controller测试,http://localhost:8802/producer/movie/test 可以换成http://localhost:8802/producer/movie/getAllMovies
package com.feng.cloud.study.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @author: fengyantao
* @date: 2019/11/6 下午4:26
* @version: V1.0
* @review: fengyantao/2019/11/6 下午4:26
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/findMovies")
public String findMovies() {
ResponseEntity<String> forEntity = restTemplate.getForEntity("http://localhost:8802/producer/movie/test", String.class);
String body = forEntity.getBody();
return body;
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
4.先后启动eureka注册中心,eureka服务提供者,eureka消费者。访问eureka注册中心,可以看到eureka消费者和eureka提供者
访问eureka-consumer路径:http://localhost:8803/consumer/user/findMovies ,可以看到结果是eureka服务提供者返回的信息
到此为止,eureka消费者eureka-consumer已经搭建完成了,代码git地址:https://github.com/fengyantao/cloud-study/tree/master
大家如果有疑问,欢迎下方留言沟通!