Eureka服务消费端搭建
1.pom.xml依赖添加
<!-- Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>eureka-consumer</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<!-- Spring Cloud -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
2.配置文件
spring:
application:
name: eureka-client-user-consumer
server:
port: 8082
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
instance:
preferIpAddress: true #采用IP注册
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port} #定义实例ID格式
3.创建启动类
@SpringBootApplication
@EnableDiscoveryClient
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
/**
* 改造RestTemplate
*/
@Bean
//这个注解会自动构造LoadBalancerClient接口的实现类并注册到Spring容器中
// 添加了这个注解才能使用restTemplate通过application.name进行调用
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
4.调用接口
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/callHello")
public String hello(){
return restTemplate.getForObject("http://eureka-client-user-service/user/hello",String.class);
}
}
//todo 5.后续补充通过Feign的方式调用