Eureka服务调用
配置文件
server:
port: 8811
spring:
application:
name: eurekaServiceClient
eureka:
instance:
hostname: localhost
prefer-ip-address: true
client:
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:8761/eureka/```
## 启动类
加上 `@EnableEurekaClient` `@EnableDiscoveryClient` 注解
`@EnableDiscoveryClient`开启服务发现功能
如果是使用Feign,需要加上`@EnableFeignClients`注解,开启Feign的使用
```java
@SpringBootApplication
@EnableEurekaClient
@Controller
public class DiscoveryClientApplication {
public static void main(String[] args) {
SpringApplication.run(DiscoveryClientApplication.class, args);
}
@RequestMapping("/")
@ResponseBody
public String main() {
return "hello";
}
}
RestTemplate
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
RestTemplate使用@LoadBalanced
注解
调用
// EUREKACLIENT 为调用的微服务名称
String remoteIpServiceUrl = "http://EUREKACLIENT/";
String result = restTemplate.getForObject(remoteIpServiceUrl, String.class);
Feign
使用@FeignClient
声明
@FeignClient("EUREKACLIENT")
public interface FeignClientService {
@RequestMapping(method = RequestMethod.GET, value = "/")
String hello();
}
使用
String result = feignClientService.hello();
return result;
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- 使用ribbon时才用的上 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<!-- 使用feign时才用的上 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>