简单的微服务实例搭建(二)
Eureka注册中心
1、在Microservices下新建maven工程:eureka:
关于服务介绍: 服务注册中心,Eureka的服务端应用,提供服务注册和发现功能
2、关于yml和pom文件:
- eureka:Eureka服务端
server:
port: 10086
eureka:
client:
service-url: # EurekaServer地址
defaultZone: http://localhost:10086/eureka
instance:
prefer-ip-address: true # 当其它服务获取地址时提供ip而不是hostname
ip-address: 127.0.0.1 # 指定自己的ip信息,不指定的话会自己寻找
spring:
application:
name: eureka # 应用名称
注意点:
eureka自身也是一个服务,需要进行注册,所以,需要在配置文件中添加上相关的注册信息
register-with-eureka:此应用为注册中心,默认为true。false->不向注册中心注册自己。
fetch-registry: 注册中心职责是维护服务实例,默认为true。false->不检索服务。
<?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">
<parent>
<artifactId>Microservices</artifactId>
<groupId>com.zpark</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>eureka</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
</project>
- service和consumer:添加Eureka客户端,注册到Eureka
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
<!-- Eureka客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.2.RELEASE</version><!--服务器有可不写-->
</dependency>
3、具体实现代码:
- eureka:添加@EnableEurekaServer注解(指明该类为Eureka服务端)
package com.zpark.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServiceApplication.class,args);
}
}
- service:添加@EnableDiscoveryClient注解(指明该类为Eureka客户端)
package com.zpark.service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("com.zpark.service.mapper")
@EnableDiscoveryClient
public class ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class,args);
}
}
4、测试:
- 依次启动:eureka、service、consumer,在网页上访问http://localhost:10086/,就会显示Eureka的详细信息
- 在网页继续访问http://localhost:8083/findall,网页依旧显示所有查询结果。