017 搭建eureka注册中心

1 eureka server

    创建一个maven工程,pom文件引入依赖:

	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
		</dependency>
	</dependencies>
	
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-starter-parent</artifactId>
				<version>Camden.SR3</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

    配置文件:application.yml

server:
  port: 8761
  
spring:
  application:
    name: eureka

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

    启动类:

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
	public static void main(String[] args) {
		SpringApplication.run(EurekaApplication.class, args);
	}
}

    启动项目并访问:http://localhost:8761/

2 注册服务

    在上一篇的 sales 和 user 项目基础上,以user项目为例,sales项目类似,修改下面的文件:

    2-1 添加 pom 依赖

    <dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
    </dependencies>
	
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-starter-parent</artifactId>
				<version>Camden.SR3</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

    2-2 更新 application.yml

server:
  port: 8081

spring:
  application:
    name: sales
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1/test?characterEncoding=UTF-8&useSSL=false
    username: root
    password: root
    
eureka:
  client:
    serviceUrl: 
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

# mybatis
mybatis:
  mapperLocations: classpath:mapper/*.xml

    2-3 修改启动类,添加 @EnableDiscoveryClient 注解

@SpringBootApplication
@EnableDiscoveryClient
public class UserApplication {
	public static void main(String[] args) {
		SpringApplication.run(UserApplication.class, args);
	}
}

    2-4 启动sales和user项目并访问:http://localhost:8761/

3 代码地址

    eureka:https://code.aliyun.com/995586041/eureka.git

    eureka_user:https://code.aliyun.com/995586041/eureka_user.git

    eureka_sales:https://code.aliyun.com/995586041/eureka_sales.git

猜你喜欢

转载自my.oschina.net/u/2937605/blog/1805337
017