springcloud Eureka 服务注册与消费发现(基于springboot搭建)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dfBeautifulLive/article/details/82458761

1.首先加入Maven依赖

1.springboot的依赖

<!--Springboot-->
	<dependency>
	 <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
        </dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>

2.springCloud服务的依赖

<!-- Eureka 服务jar包 -->
  <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
      <version>2.0.0.RELEASE</version>
  </dependency>

  <dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Finchley.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

2.添加注解和配置

在启动类加上@EnableEurekaServer注解支持 maven依赖同上文一样, 

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer //注解支持
@SpringBootApplication
public class GsaEurekaServerApplication {

	public static void main(String[] args) {
		SpringApplication.run(GsaEurekaServerApplication.class, args);
	}
}

  在application.yml添加配置信息

#配置应用名称,Eureka里就是服务名称,优先级高
spring:
    application:
        name: gsa-eureka-server
#服务端口
server:
    port: 8181

#配置应用名称,Eureka里就是服务名称
eureka:
    instance:
      hostname: localhost
    client:
      #由于该应用为注册中心,所以设置为false,代表不向注册中心注册自己
      register-with-eureka: false
      #由于注册中心的职责就是维护服务实例,它并不需要去检索服务,所以也设置为false
      fetch-registry: false

然后启动当前项目,浏览器输入http://localhost:8181/,就会看到如下页面,表示启动成功  

 2.微服务注册发现

Maven依赖还是和上文Maven一样,主要是在启动类上加入@EnableDiscoveryClient

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class GsaRestDatacenterApplication {

	public static void main(String[] args) {
		SpringApplication.run(GsaRestDatacenterApplication.class, args);
	}
}

 application.yml 配置文件

spring:
    application:
        name: gsa-rest-datacenter


#端口
server:
    port: 8686


#服务器发现注册配置
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8181/eureka/

 以上这些步骤就可以了,启动一下,就会发现在注册中心有注册进来的服务,前提是上一个Eureka服务不要忘记启动

下一节会加网关,有了网关管理,你就会发现有多么方便了,网关主要可以做路由分发,统一请求路径都请求网关服务,然后再由网关分发到各个服务里面去请求,好处是,那么多的微服务,你如果要是加过滤,加异常处理,就不会每个服务加一堆代码了,就只由网关去加就可以了,还是很方便的,一般企业都是是 springboot+springCloud+网关 去管理自己的微服务  

猜你喜欢

转载自blog.csdn.net/dfBeautifulLive/article/details/82458761