Spring Boot 搭建 Eureka Servrer · 单机模式

目录

前言

搭建 Eureka Servrer 单机模式

pom.xml 组件依赖

application.yml

@EnableEurekaServer

启动 Eureka Server

Thymeleaf 与 FreeMarker 冲突

FreeMarker 简介

使用 thymeleaf 模板

高可用性、可用区与区域


前言

1、《Netflix Eureka 简介、架构原理、及服务发现》中提到区域中会有一个 Eureka 集群,Eureka Server 之间通过复制(Replicate)的方式完成数据的同步。

2、本文件将介绍搭建 Eureka Server 单机模式,暂时不做分布式部署。Java JDK 1.8 + Spring Boot 2.1.3 + Spring Cloud(Greenwich.RELEASE) + Maven 3.5.2 + Eureka 2.1.0 + IDEA 14.

3、根据官网 “Service Discovery: Eureka Server” 文档介绍,搭建 Eureka Server 分为以下几步:

1)pom.xml 文件中引入 Eureka Server 组件:spring-cloud-starter-netflix-eureka-server

2)application.yml 中配置 Eureka Server

3)应用启动类上添加 @EnableEurekaServer 注解,声明这是一个 Eureka Server。

搭建 Eureka Servrer 单机模式

1、Java JDK 1.8 + Spring Boot 2.1.3 + Spring Cloud(Greenwich.RELEASE) + Maven 3.5.2 + Eureka 2.1.0 + IDEA 14.

2、如上所示选择了 Web 组件、Eureka Server 组件,因为 Eureka Server 服务器将来是需要提供给 Eureka Clinet 客户端进行 REST访问的,所以需要勾选 Web 组件创建 web 项目。

pom.xml 组件依赖

1、项目生成后,pom.xml 文件默认内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/>
        <!-- lookup parent from repository -->
    </parent>
    <groupId>www.wmx.com</groupId>
    <artifactId>EurekaServer_shenZhen</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>EurekaServer_shenZhen</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>

        <!-- Java web 应用时,引入 web 模块-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Eureka Server组件-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

        <!-- Spring Boot 测试组件,可要可不要-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <!-- spring cloud 依赖管理-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <!-- Maven插件-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <!-- spring仓库-->
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

</project>

application.yml

1、application.yml 中 Standalone Eureka Server)(单机 Eureka 服务器模式)配置如下:

server:
  port: 8761
#  port 也可以改为其它端口,如 8080、80

eureka:
  instance:
    hostname: 192.168.1.20
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

1)server.port:web 应用访问端口,Eureka Server 默认为 8761 端口,可以自行修改 server.port

2)eureka.instance.hostname:Eureka 实例主机名,每一个 Eureka Server 都有自己的实例名。

2)eureka.client.registerWithEureka:表示是否将自己注册到 Eureka Server 服务注册表中,默认为 true。因为当前应用本身就是 Eureka Server,所以设置为 false。Eureka Server 无需注册,Eureka Client 才需要像 Server 端进行注册。

3)eureka.client.fetchRegistry:表示是否从 Eureka Server 服务注册表中获取注册信息,默认为 true。同理自身本身就是服务端,而且是单机模式,不需要同步其他的 Eureka Server节点的数据,故而设置为 false。

4)eureka.client.serviceUrl.defaultZone:设置 Eureka Client 与 Eureka Server 交互的地址,注册、查询、注销服务都需要依赖这个地址。默认是 http://localhost:8761/eureka ;多个地址可使用 时,用 "," 分隔。其中的 ${xx} 自动取值上面的值。

5)eureka.client.serviceUrl.defaultZone 在 Eureka Server 和 Eureka Client 都会进行配置,客户端根据此地址进行请求。

@EnableEurekaServer

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

/**
 * @EnableEurekaServer :
 * 启动类上添加@EnableEurekaServer注解,声明这是一个 Eureka Server
 */
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerShenZhenApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerShenZhenApplication.class, args);
    }
}

启动 Eureka Server

eureka.client.serviceUrl.defaultZone:用于供给 Eureka Client 访问,所以 http://localhost:8761/ 访问的是 Spring Eureka 主页(也是整个应用的主页),与 defaultZone 的值无关。

启动应用后,控制台打印日志如下:

...
2019-03-05 15:46:29.446  INFO 16468 --- [      Thread-13] o.s.c.n.e.server.EurekaServerBootstrap   : Initialized server context
2019-03-05 15:46:29.447  INFO 16468 --- [      Thread-13] c.n.e.r.PeerAwareInstanceRegistryImpl    : Got 1 instances from neighboring DS node
2019-03-05 15:46:29.447  INFO 16468 --- [      Thread-13] c.n.e.r.PeerAwareInstanceRegistryImpl    : Renew threshold is: 1
2019-03-05 15:46:29.447  INFO 16468 --- [      Thread-13] c.n.e.r.PeerAwareInstanceRegistryImpl    : Changing status to UP
2019-03-05 15:46:29.465  INFO 16468 --- [      Thread-13] e.s.EurekaServerInitializerConfiguration : Started Eureka Server
2019-03-05 15:46:29.470  INFO 16468 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8761 (http) with context path ''
2019-03-05 15:46:29.470  INFO 16468 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8761
2019-03-05 15:46:29.472  INFO 16468 --- [           main] c.w.www.EurekaServerShenZhenApplication  : Started EurekaServerShenZhenApplication in 7.008 seconds (JVM running for 7.619)
2019-03-05 15:46:29.648  INFO 16468 --- [nio-8761-exec-9] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-03-05 15:46:29.648  INFO 16468 --- [nio-8761-exec-9] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-03-05 15:46:29.656  INFO 16468 --- [nio-8761-exec-9] o.s.web.servlet.DispatcherServlet        : Completed initialization in 8 ms
...

1、Eureka Server 自带了一个 web 控制台,可通过 http://localhost:8761/ 访问,注意默认情况下此时 resouces/templates模板下不能有 index.html,否则会访问不了 Spring Eureka 主页。

2、Spring Eureka 主页可以查看:

System Status(系统状态):当前 Eureka Server 的信息,如 Environment(环境)、Data center(数据中心)、当前时间、启动运行的时间等等。

DS Replicas:当前 Eureka Server 从哪些节点同步数据

Instances currently registered with Eureka:在当前 Eureka Server 上注册的实例

General Info:基本信息,如内存大小,CPU 核数,内存使用率等

Instance Info:实例信息,status :UP 表示实例正在运行

Last 1000 newly registered leases:最新1000个注册的节点

Thymeleaf 与 FreeMarker 冲突

FreeMarker 简介

1、上面示例中通过 http://localhost:8761/ 即可访问 Spring Eureka 主页,当在 resouces/templates 模板目录下创建 index.html,则访问 http://localhost:8761/ 直接报错。

2、通过依赖关系可以看出 Eureka Server 默认的使用是 freemarker 模板引擎。(市面上主流的 Java 模板引擎有:JSP、Velocity、Freemarker、Thymeleaf)

3、此时假如项目中需要使用 Thymeleaf 引擎,则默认情况下可能会导致无法正确加载 Eureka Server 的 Freemarker 模板,官方说法如下:

If your project already uses Thymeleaf as its template engine, the Freemarker templates of the Eureka server may not be loaded correctly. In this case it is necessary to configure the template loader manually:

如果您的项目中已经使用thymeleaf作为模板引擎,则可能无法正确加载Eureka服务器的FreeMarker模板。在这种情况下,需要手动配置模板加载器:

spring:
  freemarker:
    template-loader-path: classpath:/templates/
    prefer-file-system-access: false

spring.freemarker.template-loader-path:模板路径列表,多个时逗号分隔

spring.freemarker.prefer-file-system-access:是否选择文件系统访问来加载模板,文件系统访问支持对模板更改的热检测

4、关于 freemarker 模板的详细配置,可以参考官网

# FREEMARKER (FreeMarkerProperties)
spring.freemarker.allow-request-override=false # Whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name.
spring.freemarker.allow-session-override=false # Whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name.
spring.freemarker.cache=false # Whether to enable template caching.
spring.freemarker.charset=UTF-8 # Template encoding.
spring.freemarker.check-template-location=true # Whether to check that the templates location exists.
spring.freemarker.content-type=text/html # Content-Type value.
spring.freemarker.enabled=true # Whether to enable MVC view resolution for this technology.
spring.freemarker.expose-request-attributes=false # Whether all request attributes should be added to the model prior to merging with the template.
spring.freemarker.expose-session-attributes=false # Whether all HttpSession attributes should be added to the model prior to merging with the template.
spring.freemarker.expose-spring-macro-helpers=true # Whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext".
spring.freemarker.prefer-file-system-access=true # Whether to prefer file system access for template loading. File system access enables hot detection of template changes.
spring.freemarker.prefix= # Prefix that gets prepended to view names when building a URL.
spring.freemarker.request-context-attribute= # Name of the RequestContext attribute for all views.
spring.freemarker.settings.*= # Well-known FreeMarker keys which are passed to FreeMarker's Configuration.
spring.freemarker.suffix=.ftl # Suffix that gets appended to view names when building a URL.
spring.freemarker.template-loader-path=classpath:/templates/ # Comma-separated list of template paths.
spring.freemarker.view-names= # White list of view names that can be resolved.

使用 thymeleaf 模板

1、通过官网介绍以及上面的分析 Eureka Server 使用 Thymelaf 模板引擎,只需要在 application.yml 中配置 FreeMarker模板即可。

2、在上面的基础上修改 pom.xml 文件如下,追加 Thymelaf 组件:

<!-- 引入thymeleaf模板引擎-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

3、在上面的基础上追加修改 application.yml 文件如下,设置 FreeMarker 模板不从文件系统加载:

server:
  port: 8761
#  port 也可以改为其它端口,如 8080、80

eureka:
  instance:
    hostname: 192.168.1.20
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

#配置 freemarker 模板引擎,不从文件系统加载模板
spring:
  freemarker:
    template-loader-path: classpath:/templates/
    prefer-file-system-access: false

4、为了演示 Thymeleaf 的功能,这里新建一个控制层,然后页面访问控制层,控制层跳转到 resources/templates 模板目录下。

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * Created by Administrator on 2019/3/5 0005.
 * 控制器层
 */
@Controller
public class InfoController {

    /**
     * 页面请求:http://localhost:8761/info
     *
     * @return
     * @ResponseBody :表示将返回值直接输出到页面
     */
    @ResponseBody
    @GetMapping("info")
    public String info() {
        return "Success:" + new Date();
    }

    /**
     * 页面请求:http://localhost:8761/login
     * 自动跳转到默认的 classpath:/templates/login.html 页面
     *
     * @return
     */
    @GetMapping("login")
    public String login() {
        return "login";
    }
}

5、templates/login.html 内容如下:

6、启动应用,访问测试:

如上所示使用 Thymeleaf 模板引擎完全成功,不过因为 Spring Eureka 占用了 index.html 主页,在 resources/templates 下自己新建 index.html时,此时访问 http://localhost:8761/ 虽然不会报错,但是默认还是访问的 Spring Eureka 而不是自己的 index.html,解决方法是自己不使用 index.html 名称就是了。

高可用性、可用区与区域

1、摘自官网:https://cloud.spring.io/spring-cloud-static/spring-cloud-netflix/2.1.0.RELEASE/single/spring-cloud-netflix.html#spring-cloud-eureka-server-zones-and-regions

The Eureka server does not have a back end store, but the service instances in the registry all have to send heartbeats to keep their registrations up to date (so this can be done in memory). Clients also have an in-memory cache of Eureka registrations (so they do not have to go to the registry for every request to a service).

By default, every Eureka server is also a Eureka client and requires (at least one) service URL to locate a peer. If you do not provide it, the service runs and works, but it fills your logs with a lot of noise about not being able to register with the peer.

See also below for details of Ribbon support on the client side for Zones and Regions.

2、Eureka 服务器没有后端存储,但注册中心中的服务实例都必须发送心跳以保持其注册是最新的(因此这可以在内存中完成)。客户端还有一个Eureka注册的内存缓存(因此他们不必为每个服务请求都到注册中心)。默认情况下,每个Eureka服务器也是一个Eureka客户机,需要(至少一个)服务URL来定位一个对等点。如果您不提供它,服务仍然会运行并正常工作,但是它会让您的日志中充满关于无法向对等方注册的大量干扰信息。

3、Eureka 可以将服务器配置和部署为高可用,每个服务器都将注册服务的状态复制到其他服务器。

猜你喜欢

转载自blog.csdn.net/wangmx1993328/article/details/88181039
今日推荐