2019独角兽企业重金招聘Python工程师标准>>>
二, 创建 spring cloud 项目spring cloud Finchley 官方文档: http://cloud.spring.io/spring-cloud-static/Finchley.RELEASE/single/spring-cloud.html
spring cloud 微服务的 重要环节就是 服务的注册于发现 , 而 服务注册中心组件就是 : Eureka
1, 新建 Maven 项目 cloud, 作为 父包使用 :
pom.xml :
2, 新建模块Module Spring Boot 项目 cloud-a, 作为服务的注册中心
只需引用Eureka服务包即可:
1, cloud-a pom.xml:
2, 注册中心配置: application.yml :
# http://localhost:8761/ 可访问 eureka server 界面
server:port: 8761eureka:instance:hostname: localhost # 服务IPclient:registerWithEureka: falsefetchRegistry: false# 注册地址serviceUrl:defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
# 服务名称
spring:application:name: eurka-server
3, 注册中心启动类 CloudAApplication :
package com.gy.cloud.clouda;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;@EnableEurekaServer
@SpringBootApplication
public class CloudAApplication {public static void main(String[] args) {SpringApplication.run(CloudAApplication.class, args);System.out.println("=== 启动服务注册中心成功 ===");}
}
5, 注册中心启动成功后访问: http://localhost:8761/
简单的注册中心就搭建完成;
3, 新建 客户端服务 cloud-b , 向整个项目提供服务 :
cloud-b pom.xml :
cloud-b application.yml :
server:port: 8762# 服务名称
spring:application:name: service-b# 服务注册地址
eureka:client:serviceUrl:defaultZone: http://localhost:8761/eureka/
cloud-b 启动类 CloudBApplication :
package com.gy.cloud.cloudb;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@EnableEurekaClient
@SpringBootApplication
public class CloudBApplication {public static void main(String[] args) {SpringApplication.run(CloudBApplication.class, args);System.out.println("=== 服务B启动成功 === ");}@Value("${server.port}")private String port;@GetMapping("/hi")public String home(String name) {name = name == null ? "SERVICE-B" : name;return "Hi " + name + " , I am from port: " + port;}}
服务B配置完成, 启动成功后,查看: http://localhost:8761/
SERVICE-B 就会注册到 Eureka 中 ;
学习文档方志朋的博客 : https://www.fangzhipeng.com/springcloud/2018/08/30/sc-f1-eureka/
项目源码: https://gitee.com/ge.yang/spring-demo/tree/master/cloud