Eureka分为Eureka-Server,其他服务就变成Eureka-Client
Eureka实际就是一个注册中心,相当于我们的生活中的媒婆。
Eureka实际运行机制
综合上述机制,就是实现了注册中心的功能。
服务端
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>配置文件
# Eureka-Server配置信息
server.port=8090
spring.application.name=Eureka-Server
# 将自己注册到Eureka,自己即是服务端,也是客户端,作为客户端到原因时为了方便Eureka服务端集群使用,多个使用逗号隔开
eureka.client.service-url.defaultZone=http://127.0.0.1:8090/eureka启动类
@SpringBootApplication
@EnableEurekaServer // 指定为Eureka-Server
@Slf4j
public class XxEurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(XxEurekaServerApplication.class, args);
System.out.println("项目启动成功后去访问本服务http://localhost:8090/ 就会展示Eureka的Dashpoard");
}
}启动项目,等待30秒,访问:127.0.0.1:8090
客户端使用
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency># Eureka-Client配置信息
server.port=8091
spring.application.name=Eureka-Client
# 将自己注册到Eureka
eureka.client.service-url.defaultZone=http://127.0.0.1:8090/eureka启动类
@SpringBootApplication
@EnableEurekaClient // 指定为Eureka-Client
@Slf4j
public class XxEurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(XxEurekaClientApplication.class, args);
}
@Bean
@LoadBalanced // 默认也就是负载均衡
public RestTemplate initRest() {
return new RestTemplate();
}
}任意一个Controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class DiyController {
@RequestMapping("/abc")
public String hello() {
System.out.println("请求进来了");
return "OK";
}
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/go")
public String 模拟负载均衡请求() {
// 测试远程调用
ResponseEntity<Object> forEntity = restTemplate.getForEntity("http://EUREKA-CLIENT/abc", null);
System.out.println("请求进来了");
return "OK";
}
}启动项目,等待30秒,访问:127.0.0.1:8090 Eureka注册其中心就有个下文

我们到此就完成了服务的注册。
服务发现如何体现呢?
我们接着直接测试,http://127.0.0.1:8091/go,其利用RestTemplate发送GET请求,指向的地址就不是固定写死的了,而是通过向Eureka获取的目标服务地址来发送请求了,请求EUREKA-CLIENT,就代表上图的192.168.0.106: 8091或者8092了。
到从Eureka的注册与发现就完成了!
但是Eureka只有服务注册与发现,实现的负载均衡就是的Ribbon(你可以点击一下@Loadbalance注解看一下):https://cloud.tencent.com/developer/article/2080991
特殊说明: 以上文章,均是我实际操作,写出来的笔记资料,不会盗用别人文章!烦请各位,请勿直接盗用!转载记得标注来源!