## 微服务学习打卡-Eureka
简介:
Eureka是Netflix开发的服务发现框架,本身是一个基于REST的服务,主要用于定位运行在AWS域中的中间层服务,以达到负载均衡和中间层服务故障转移的目的。SpringCloud将它集成在其子项目spring-cloud-netflix中,以实现SpringCloud的服务发现功能。
作用:
直接整案例:
一.
搭建eureka注册中心:
1. 在父工程下新建一个maven工程:eureka-server
2. 在pom.xml里边引入依赖:
org.springframework.cloud
spring-cloud-starter-eureka-server
1.4.7.RELEASE
3.编写启动类,添加@EnableEurekaServer注解
package com.itcast.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class);
}
}
4.添加application.yml文件,编写下面的配置:
server:
port: 8082
spring:
application:
name: eurekserver #服务名称
eureka:
client:
service-url: #eureka地址信息
defaultZone: "http://127.0.0.1:8082/eureka"
二.将user-service注册到eureka注册中心
1.在对应工程user-service添加对应依赖:
--> org.springframework.cloud spring-cloud-starter-netflix-eureka-client
2.在yml中进行配置:
spring:
application:
name: userservice #服务名称
eureka:
client:
service-url: #eureka地址信息
defaultZone: "http://127.0.0.1:8082/eureka"
完成
三:将order-service注册到eureka中,步骤相同。
到此就完成了服务注册和发现。
服务拉取:
在上一篇文章中我们知道了使用restTemplete进行服务远程调用:
RsetTemplate发起:string url="http://127.0.0.1:8080/user/"+order.getUserId()
现在学习了eureka注册中心后就可以用服务名来代替ip和端口号:
String url = "http://userservice/user/" + order.getUserId();
在order-service项目的启动类OrderApplication中的RestTemplate添加负载均衡注解:
//负载均衡
@LoadBalanced
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
今天学习到此结束。



