先说一说微服务有哪些东西,如果是全家桶的话非常的多,大概是下面这些
Spring Cloud Config
Spring Cloud Netflix
Spring Cloud Bus
Spring Cloud Cloudfoundry
Spring Cloud Open Service Broker
Spring Cloud Cluster
Spring Cloud Consul
Spring Cloud Security
Spring Cloud Sleuth
Spring Cloud Data Flow
Spring Cloud Stream
Spring Cloud Stream App Starters
Spring Cloud Task
Spring Cloud Task App Starters
Spring Cloud Zookeeper
Spring Cloud AWS
Spring Cloud Connectors
Spring Cloud Starters
Spring Cloud CLI
Spring Cloud Contract
Spring Cloud Gateway
Spring Cloud OpenFeign
Spring Cloud Pipelines
Spring Cloud Function
但,其实真正常用的就那么几个:
服务注册中心
路由(新版本的zuul已经集成了Ribbon负载均衡和熔断并且一般在zuul中就已经完成一体化拦截,认证)
消息总线(非刚需)
远程配置(非刚需)
说白了刚需的就两个东西,搭起来就能用
下面开始搭建
1.搭建注册中心
新建一个springboot 项目,取名叫parent,我这里用的是
2.1.9.RELEASE
别问为什么不用最新版,问就是不会
parent项目中定义一下各种基础的起步依赖,打包类型修改为pom
pom
然后再新建一个springboot 项目,继承一下刚才的parent项目,后面所有springcloud组件都继承parent,服务提供者最好不用继承,以后团队开发没必要每个人都是一大坨东西,非要继承也行
com.xxx.springcloud springcloud-service-parent1.0.0 ../springcloud-service-parent/pom.xml
然后dependencies中加入依赖
org.springframework.boot spring-boot-starter-weborg.springframework.cloud spring-cloud-starter-netflix-eureka-server
然后application.yml中加入配置,如果是properties的建议改成yml,避免后面遇上各种坑
server:
port: 8848
# 该服务注册中心的hostname
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://localhost:8848/eureka
好了,最简单的注册中心已经弄好,下一个
2.搭建路由,网上很多教程这一步肯定是让你去弄Ribbon或feign,其实不需要,很多人都只会给你讲皮毛的东西,真正实战以后,那个东西根本就没办法用,就拿feign来说,每一个请求都要去申明一下,创建一个service接口,用controller去调用接口,相当于正常开发的时候每个接口都要写两遍,美其名曰申明式调用。
新建一个springboot项目,继承parent,pom中添加依赖
org.springframework.boot spring-boot-starter-weborg.springframework.cloud spring-cloud-starter-netflix-eureka-clientorg.springframework.cloud spring-cloud-starter-netflix-zuul
配置文件如下
spring:
application:
name: zuul
server:
port: 8888
eureka:
client:
service-url:
defaultZone: http://localhost:8848/eureka
instance:
#每间隔2s,向服务端发送一次心跳,证明自己依然"存活"
lease-renewal-interval-in-seconds: 2
#告诉服务端,如果我10s之内没有给你发心跳,就代表我故障了,将我踢出掉
lease-expiration-duration-in-seconds: 10
#告诉服务端,服务实例以IP作为链接,而不是取机器名
prefer-ip-address: true
#告诉服务端,服务实例的名字
instance-id: springcloud-service-zuul
#配置熔断时间,使用service-id
ribbon:
ReadTimeout: 20000
ConnectTimeout: 20000
#配置熔断时间,使用url
zuul:
host:
connect-timeout-millis: 20000
connection-request-timeout-millis: 20000
routes:
# 替换路径中的服务名,第一级随便指定主要用于区分
goods:
service-id: goods
path: /work/**
goods2:
service-id: goodWork
path: /w/**
# 设置不允许通过服务名访问
ignored-services: '*'
# 设置前缀
prefix: /api
需要说明的几个东西,组件名称要使用
spring:
application:
name: zuul
使用eureka 的appname虽然能正确显示,但是在整个体系中是认不出来的
自己指定路由的时候多个就用routes下的那一级分开,就像上面的goods和goods2,goods和goods可以随便写,自己知道用来区分哪个就好了
访问的时候http://路由ip:端口/前缀/替换的path/服务提供的路径
这样就能直接访问了
下面说一下负载均衡,上面的zuul已经集成了负载均衡了,我们在服务提供组件里面使用相同的application name就可以
spring:
application:
name: goods
你访问goods的时候就会自动负载了,具体要采用哪种负载方法自己去陪一下,轮询,加权等
到这里最基本的spring cloud 架构就成了
下一步在zuul中加入拦截,用户权限认证
下一步是解决组件安全的问题,不可能什么服务都能随便加进来,需要引入spring security简单配置一下加个密码什么的就行了



