springcloud服务注册中心Eureka
启动一个服务注册中心,只需要一个注解@EnableEurekaServer
package com.dalingjia.eurekaserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* 启动一个服务注册中心,只需要一个注解@EnableEurekaServer
*/
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
配置文件如下,表明自己是一个服务注册中心:
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
Eureka客服端,通过注解@EnableEurekaClient表明自己是一个eurekaClient:
/**
* 通过注解@EnableEurekaClient 表明自己是一个eurekaclient.
*/
@SpringBootApplication
@EnableEurekaClient
@RestController
@EnableHystrix
@EnableHystrixDashboard
public class ServiceHiApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceHiApplication.class, args);
}
}
客户端配置:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8762
spring:
application:
name: service-hi
启动服务端和客户端,访问localhost:8761,可以看到注册到eureka的当前实例:
@EnableDiscoveryClient与@EnableEurekaClient区别
简而言之 spring cloud 中服务发现有多种实现(eureka、consul、zookeeper等等),@EnableDiscoveryClient 基于 spring-cloud-commons, @EnableEurekaClient 基于 spring-cloud-netflix。
一句话:如果选用eureka做注册中心,那么推荐@EnableEurekaClient;如果不是eureka,那么推荐使用@EnableDiscoveryClient。
@EnableEurekaClient源码如下:
package org.springframework.cloud.netflix.eureka;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface EnableEurekaClient {
}
@EnableDiscoveryClient源码如下:
package org.springframework.cloud.client.discovery;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({EnableDiscoveryClientImportSelector.class})
public @interface EnableDiscoveryClient {
boolean autoRegister() default true;
}
还没有评论,来说两句吧...