什么是微服务?
将一个单体应用拆分成一组微小的服务组件,每个微小的服务组件运行在自己的进程上,组件之间通过如Restful API 这样的轻量级机制进行交互,这些服务以业务能力为核心,用自动化部署机制独立部署,另外,这些服务可以用不同语言研发,用不同技术来存储数据。
什么是Spring Cloud?
Spring Cloud 为开发人员提供了快速构建分布式系统的一些工具,包括配置管理、服务发现、断路器、路由、负载均衡、微代理、事件总线、全局锁、决策竞选、分布式会话等等。
Spring Cloud 是通过一个中心:eureka(注册中心),不同service通过rpc进行互通。
下面记录Spring Boot 整合 Spring Cloud的过程!
注册中心:
使用注解
@EnableEurekaServer
启动类:
package io.ymq.example.eureka.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
加入相应的依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
此外,往pom中加入dependencyManagement
的配置
<dependencyManagement>
<dependencies>
<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>
application.yml
配置:
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
spring:
application:
name: eureka-service
server:
port: 8888
eureka.client.registerWithEureka
:表示是否将自己注册到Eureka Server,默认为true。
eureka.client.fetchRegistry
:表示是否从Eureka Server获取注册信息,默认为true。
eureka.client.serviceUrl.defaultZone
:设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址。默认是http://localhost:8761/eureka ;多个地址可使用 , 分隔。
然后启动注册中心。
浏览器访问http://localhost:8888/
就可以看到注册中心已经启动了!
此时图中红框部分表示还不存在服务Service.