在Eureka架构中,微服务角色有两类:
1.搭建EurekaServer
引入eureka-server依赖
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
dependency>
添加@EnableEurekaServer注解
@SpringBootApplication
@EnableEurekaServer
public class EurekaMain{
public static void main(String[] args) {
SpringApplication.run(EurekaMain.class, args);
}
}
在application.yml中配置eureka地址
server:
port: 7001
eureka:
instance:
hostname: eureka-server
client:
# 不向注册中心注册自己
register-with-eureka: false
# 表示自己是注册中心,提供维护服务,不需要检索服务
fetch-registry: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka
2.服务注册
引入eureka-client依赖
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>
在application.yml中配置eureka地址
eureka:
client:
fetch-registry: true
register-with-eureka: true
service-url:
defaultZone: http://localhost:7001/eureka
instance:
instance-id: payment
启动类上加注解
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class PaymentMain {
public static void main(String[] args) {
SpringApplication.run(PaymentMain.class, args);
}
}
3.服务发现
引入eureka-client依赖
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>
在application.yml中配置eureka地址
eureka:
client:
fetch-registry: true
register-with-eureka: true
service-url:
defaultZone: http://localhost:7001/eureka
spring:
application:
name: cloud-order-service
给RestTemplate添加@LoadBalanced注解
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@RestController
@Slf4j
public class OrderController {
public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
@Resource
private RestTemplate restTemplate;
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment) {
return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
}
eureka:
server:
enable-self-preservation: false #默认开启
eviction-interval-timer-in-ms: 2000 #2s