1.创建子工程并导入依赖
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ssmspringboot2</artifactId>
<groupId>com.example</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>provider-service</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<!--<version>Finchley.RC1</version>-->
<version>Edgware.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.yml</include>
</includes>
</resource>
</resources>
</build>
</project>
2.配置application.yml文件
server:
port: 8890
spring:
application:
name: consumer-service
eureka:
client:
service-url:
defaultZone: http://localhost:8888/eureka/
instance:
hostname: localhost
prefer-ip-addrss: false #使用ip地址注册
3.配置启动类
在启动类上面添加注解 @EnableEurekaServer
@EnableEurekaClient
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
}
4.注入DisCoveryClient,进行远程调用
package test.controller;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.client.http.HttpRequest;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import test.entity.Student;
import java.util.List;
@Controller
public class testController {
@Autowired
private DiscoveryClient product;
@RequestMapping("test")
@ResponseBody
public String test(HttpRequest req, Model model){
List<ServiceInstance> instances = product.getInstances("PROVIDER-SERVICE");
ServiceInstance serviceInstance = instances.get(0);
RestTemplate r = new RestTemplate();
String x = r.getForObject("http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/test", Student.class).toString();
return x;
}
}