Spring Cloud Netflix组件Erueka, Erueka是一个服务注册与发现模块。
服务的注册与发现类似与消息的生产者与消费者,服务注册即生产消息,服务发现即消息的订阅与拉取。配置服务注册中心,好处在于,我们不需要知道究竟有多少服务供我们使用,只需要关注服务注册中心是否存在我们想要使用的服务。即,当我们需要调用某一个服务的时候,首先会到Eureka中去拉取服务列表,如果存在对应的服务,则获取对应的信息进行相应的调用请求。
Erueka的实现
1. 创建服务注册中心
@EnableEurekaServer
@SpringBootApplication
public class EruekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EruekaServerApplication.class, args);
}
}
这里面EnableEurekaServer就是用来启用服务注册中心的,然后配置相应的注册中心信息
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
配置的端口号8761, 要把registerWithEureka和fetchRegistry参数设为false,这样就可以设置成为一个注册中心了。
启动appliation可以看到一个web页面
接下来在客户端注册一个服务
@EnableEurekaClient
@SpringBootApplication
@RestController
public class EruekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EruekaClientApplication.class, args);
}
@Value("${server.port}")
Stringport;
@Value("${spring.application.name}")
StringapplicaitonName;
@RequestMapping("/hi")
public Stringhi(@RequestParam String name) {
return "welcome " + name +", from " +applicaitonName +": "+port;
}
}
EnableEurekaClient使用在启用其为eureka客户端,相应的客户端配置如下
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8762
spring:
application:
name: erueka-client-1
这里需要注意service要写上对应注册中心的url,application name要写清楚,这会在注册与发现服务中使用的。启动客户端程序,可以看到在服务注册中心成功注册来一个服务。
这样简单的Erueka服务注册中心就搭建起来了。
网友评论