天天看点

spring cloud 服务注册中心

创建“服务注册中心”

spring cloud的学习都是建立在spring boot基础上的,所以对spring boot不了解的童鞋先要了解下spring boot项目的搭建以及运行机制。

1.创建springBoot项目

spring cloud 服务注册中心

2.并在pom.xml中引入需要的依赖

<dependencies>
    <!--eureka 服务依赖,将来其他服务注册就是注册到这个项目下,类似于dubbo使用zookeeper作为注册中心-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka-server</artifactId>
    </dependency>
   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
   </dependency>
</dependencies>
<!--用来管理spring cloud,在 <dependency>标签中引用spring cloud的组件就不需要指定版本信息 -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Brixton.SR5</version><!-- 最好使用一些新的版本 -->
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
           

3.在application.properties中添加配置

server.port=
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/
           

eureka端口,和其他项目区分,保持独立

server.port=8761

配置主机名

eureka.instance.hostname=eureka-server-01

配置服务注册中心是否以自己为客户端进行注册(配置false)

eureka.client.registerWithEureka=fasle

是否取得注册信息(配置false)

eureka.client.fetchRegistry=false

配置eureka客户端的缺省域(该配置可能没有提示,请复制或者手动输入,切勿使用有提示的service-url会引起内置tomcat报错)

eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka

4.在入口文件中开启服务注册中心

package com.example;

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

@SpringBootApplication
@EnableEurekaServer
public class SpringCloudServerApplication {

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

5.启动项目

访问:http://localhost:8761/

spring cloud 服务注册中心

这样注册中心就好了,下面就可以将服务注册到注册中心,供消费者调用,大家也许会想一个事,如果注册中心宕机了那不是就惨了吗?所有调用将死去,是的,所以搭建高可用的注册中心是非常重要的。

一般来说,搭建高可用的注册中心架构人员会做,无需普通开发人员关心,其实在spring cloud环境下工作很多事情变得比较容易,下一篇博文我们来搭建高可用的注册中心。

想了解更多java相关技术,请关注公众号“JavaEE那些事”

扫描下面二维码,更多技术资料等你来拿

spring cloud 服务注册中心

继续阅读