spring cloud开发基本教程

目录

Eureka注册中心

简单注册中心搭建

其它配置详解

 Eureka-注册中心集群配置

双节点注册中心

 eureka集群使用

服务模块

简单服务模块搭建(往注册中心注册服务)

 其它配置详解

Zuul网关

简单zuul网关搭建(实现网关路由)

其他配置详解

路由规则详解

路由其他组件详解

Ribbon

Hystrix

Feign

Stream

Bus

Sleuth

Dashboard

Config


Eureka注册中心

简单注册中心搭建

  • 新建spring boot 项目(可根据实际需求建maven模块)  详情可查看
  • 添加pom依赖
                
			org.springframework.cloud
			spring-cloud-starter-eureka-server
		
  • 添加配置信息(配置文件支持properties和yml两种格式,这里以properties文件为例)
#设置端口号
server.port=8761
#设置eureka相关配置
eureka.instance.hostname=localhost
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
  • 启动项添加注解
@EnableEurekaServer

 @EnableEurekaServer不可以是添加


		
			
				org.springframework.cloud
				spring-cloud-dependencies
				
				Edgware.SR4
				pom
				import
			
		
	

 

其它配置详解

#服务注册中心实例的主机名
eureka.instance.hostname=localhost
#是否向服务注册中心注册自己,为false就是只作为注册中心,不向外提供服务
eureka.client.register-with-eureka=false
#是否检索服务
eureka.client.fetch-registry=false
#自我保护配置,可以设置改参数值为false,以确保注册中心将不可用的实例删除
eureka.server.enable-self-preservation=false
#清理无效节点的时间间隔,默认60000毫秒,即60秒
eureka.server.eviction-interval-timer-in-ms=60

 Eureka-注册中心集群配置

双节点注册中心

同上述步骤新建两个注册中心,分别修改其配置文件

server.port=8000
spring.application.name=spring-cloud-eureka
eureka.instance.hostname=service1
#作为service1服务中心的配置,并将serviceUrl指向service2
eureka.client.serviceUrl.defaultZone=http://service2:8001/eureka/
spring.application.name=spring-cloud-eureka
server.port=8001
eureka.instance.hostname=service2
#作为service2服务中心的配置,并将serviceUrl指向service1
eureka.client.serviceUrl.defaultZone=http:/service1:8000/eureka/

在hosts文件中加入如下配置

127.0.0.1 service1  
127.0.0.1 service2  

 依次执行下面命令

#打包
mvn clean package
# 分别以service1和service2 配置信息启动eureka;spring-cloud-eureka-0.0.1-SNAPSHOT.jar为所打项目jar包
java -jar spring-cloud-eureka-0.0.1-SNAPSHOT.jar --spring.profiles.active=service1
java -jar spring-cloud-eureka-0.0.1-SNAPSHOT.jar --spring.profiles.active=service2

 eureka集群使用

同上述步骤新建两个注册中心,分别修改其配置文件

spring.application.name=spring-cloud-eureka
spring.profiles=service1
server.port=8000
eureka.instance.hostname=service1
eureka.client.serviceUrl.defaultZone=http://service2:8001/eureka/,http://service3:8002/eureka/


spring.application.name=spring-cloud-eureka
spring.profiles=service2
server.port=8001
eureka.instance.hostname=service2
eureka.client.serviceUrl.defaultZone=http://service1:8000/eureka/,http://service3:8002/eureka/


spring.application.name=spring-cloud-eureka
spring.profiles=service3
server.port=8002
eureka.instance.hostname=service3
eureka.client.serviceUrl.defaultZone=http://service1:8000/eureka/,http://service2:8001/eureka/

分别以service1、service2、service3的配置参数启动eureka注册中心。

java -jar spring-cloud-eureka-0.0.1-SNAPSHOT.jar --spring.profiles.active=service1
java -jar spring-cloud-eureka-0.0.1-SNAPSHOT.jar --spring.profiles.active=service2
java -jar spring-cloud-eureka-0.0.1-SNAPSHOT.jar --spring.profiles.active=service3

 Eureka密码配置

添加pom依赖:


   org.springframework.boot
   spring-boot-starter-security

 添加配置:

# 安全认证的配置(注册中心配置)
security.basic.enabled=true
#账户
security.user.name=admin
#密码
security.user.password=123456
#服务模块配置,用于配置注册中心地址
eureka.client.service-url.defaultZone=http://admin:123456@localhost:8761/eureka/

 


服务模块

简单服务模块搭建(往注册中心注册服务)

  • 新建spring boot项目(可根据实际需求建maven模块) 
  • 添加pom依赖
                
			org.springframework.cloud
			spring-cloud-starter-eureka
		
  • 添加配置信息
#配置端口号
server.port=8762
#配置注册中心地址
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
#配置服务名
spring.application.name=user-service
  • 启动类添加注解
@EnableEurekaClient

 其它配置详解

#是否需要去检索寻找服务,默认是true
eureka.client.fetch-registry=true
#表示eureka client间隔多久去拉取服务注册信息,默认为30秒,对于gateway,如果要迅速获取服务注册状态,可以缩小该值,比如5秒
eureka.client.registry-fetch-interval-seconds=5
#修改实例的状态页面地址,相对路径,也支持绝对路径,例如需要支持https,默认为/info
eureka.instance.health-check-url-path=/xxx/health
#修改健康监控地址,相对路径,也支持绝对路径,例如需要支持https,默认为/health
eureka.instance.status-page-url-path=/yyy/info
#表示eureka client发送心跳给server端的频率,默认5秒
eureka.instance.lease-renewal-interval-in-seconds=5
#表示eureka server至上一次收到client的心跳之后,等待下一次心跳的超时时间;超时移除该instance
eureka.instance.lease-expiration-duration-in-seconds=90

 


Zuul网关

简单zuul网关搭建(实现网关路由)

  • 新建spring boot 项目(可根据实际需求建maven模块) 
  • 添加pom依赖
                
			org.springframework.cloud
			spring-cloud-starter-eureka
		
		
			org.springframework.cloud
			spring-cloud-starter-zuul
		
  • 添加配置信息
#配置端口号
server.port=5000
#配置服务名
spring.application.name=gateway-service
#配置注册中心地址
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
#配置网关过滤的url前缀
zuul.routes.api-a.path=/user-api/**
#配置网关路由的服务
zuul.routes.api-a.serviceId=user-service
  • 添加zuul网关过滤器
package com.filter;

import com.netflix.zuul.ZuulFilter;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

@Component
public class DemoFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }
    @Override
    public int filterOrder() {
        return 900;
    }
    @Override
    public boolean shouldFilter() {
        return true;
    }
    @Override
    public Object run() {
        //可以用来进行登录验证,验签等操作
        return null;
    }
}
  • 启动类添加注解
@EnableZuulProxy
@EnableEurekaClient

其他配置详解

#该参数用来开启重试机制
spring.cloud.loadbalancer.retry.enabled=true
#断路器的超时时间,断路器的超时时间需要大于ribbon的超时时间,不然不会触发重试。
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=10000
#ribbon请求连接的超时时间
ribbon.ConnectTimeout=250
#请求处理的超时时间
ribbon.ReadTimeout=1000
#对所有操作请求都进行重试
ribbon.OkToRetryOnAllOperations=true
#对当前实例的重试次数
ribbon.MaxAutoRetries=1
#对下个实例的重试次数
ribbon.MaxAutoRetriesNextServer=1
#为路由规则设置公共的前缀
zuul.prefix=/myapi
#关闭全局重试机制
zuul.retryable=false
#关闭服务的重试机制
zuul.routes..retryable=false

反向代理(通过url路由)

zuul.routes.user.path: /user/**
#访问路径/user跳转到百度页面
zuul.routes.user.url: http://www.baidu.com

通过Eurek服务路由

zuul.routes.api-a.path=/user-api/**
#访问路径/user-api/xxx/yyy可访问到user-service服务上的/xxx/yyy接口
zuul.routes.api-a.serviceId=user-service

#等同于上面两行配置    zuul.routes.<服务名>=<路由规则>
zuul.routes.user-service=/user-api/**

路由到本地(网关服务)

zuul.routes.local.path=/local/**
#访问/local路由到本地(网关)的/user/local接口
zuul.routes.local.url=forward:/user/local

路由规则详解

通配符 含义 举例 解释
? 匹配任意单个字符 /demo/? 匹配 /demo/a
* 匹配任意数量的字符 /demo/*

匹配 /demo/abc

但不可匹配 /demo/a/b/c

** 匹配任意数量的字符 /demo/**

匹配 /demo/abc

也可匹配 /demo/a/b/c

 

注: 网关的配置文件最好才用yaml配置,因为在yml文件上配置路由有顺序,上面配配好就匹配下面了,例如:

zuul:
 routes:
  feign-consumer-hello:
   path: /feign-consumer/hello/**
   serviceId: feign-consumer-hello
  feign-consumer:
   path: /feign-consumer/**
   serviceId: feign-consumer

访问/feign-consumer/hello/**会路由到服务feign-consumer-hello,虽然/feign-consumer/hello/**也符合路由规则

/feign-consumer/hello/**,但因为/feign-consumer/hello/**配置在前,则路由到feign-consumer-hello.

其他组件详解

Ribbon

客户端负载均衡,特性有区域亲和、重试机制。

(1) 简单应用

新建spring boot,服务注册到注册中心(一个简单的服务模块)

添加pom依赖:

                
			org.springframework.cloud
			spring-cloud-starter-netflix-ribbon
			1.4.4.RELEASE
		

启动类上加配置:

        // 这里是重点 加上它才能使用ribbon负载
        @Bean
	@LoadBalanced
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}

新建 Controller,实现负载均衡

package com.forezp.web;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
 
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/demo")
    public String demo(){
        /*
         * 使用restTemplate调用,YST-RIBBON-ONE 为服务名 即spring.application.name
         * 启动两个 YST-RIBBON-ONE 则会进行负载调用
         */
        return restTemplate.getForObject("http://RIBBON-SERVICE/user/hi",String.class);
    }
}

注: 实现负载均衡,必须有两个及以上服务注册到同一个服务名上,必须都有同一个接口,否则报404.上面的demo没有配置分配规则,默认为轮回规则

(2) 服务分配规则配置

方法一: 配置文件

#service-B是注册到Eureka的serviceID 那个大写的东东 千万别写成application.name了
service-B.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule

方法二:配置bean

package com.forezp.config;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TestConfiguration {
    @Bean
    public IRule ribbonRule(){
        // 随机规则 这里可以定义其他规则
        return new RandomRule();
    }
}

(3) ribbon不在eureka注册服务的使用配置

ribbon.eureka.enabled=false
#service-B服务名
service-B.ribbon.listOfServers=localhost:9001,localhost:9002

Hystrix

客户端容错保护,特性有服务降级、服务熔断、请求缓存、请求合并、依赖隔离。

(1) 与Feign一起用,完成调用失败处理

新建spring boot,服务注册到注册中心(一个简单的服务模块,与要调的服务同注册中心)

添加pom依赖:


    org.springframework.cloud
    spring-cloud-starter-feign


    org.springframework.cloud
    spring-cloud-starter-hystrix

 编写调用服务的接口:

package com.goku.demo.remote;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
//spring-cloud-producer为要调的服务名  ExampleRemoteHystrix.class调用失败处理类
@FeignClient(name= "spring-cloud-producer", fallback = ExampleRemoteHystrix.class)
public interface  ExampleRemote {
//与服务提供方配的路径一致
    @RequestMapping("/test")
     String echo(String str);
}

 编写调用失败处理类:

package com.goku.demo.remote;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

@Component
public class ExampleRemoteHystrix implements ExampleRemote {
    @Override
    public String echo(String str) {
        return " 调用失败,请重试";
    }
}

启动类加注解:

@EnableFeignClients

 使用时调服务的接口就行.

Feign

声明式服务调用,本质上就是Ribbon+Hystrix

(1) 服务提供方

(2) 服务调用方

项目模块已注册到注册中心

添加pom依赖:


    org.springframework.cloud
    spring-cloud-starter-openfeign
    1.4.4.RELEASE

 编写调用服务的接口:

package com.forezp.feign;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@FeignClient(name="ribbon-demo")
public interface FeignDemo {
    @RequestMapping(value="/test/demo",method= RequestMethod.GET)
    String feignDemo();
}

 启动类上添加注解:

/*
com.forezp.feign为接口所在的包
*/
@EnableFeignClients("com.forezp.feign")

 使用时调用接口即可

zipkin

zipkin项目模块已注册到注册中心

添加pom依赖:


    io.zipkin.java
    zipkin-server
    2.7.1


    io.zipkin.java
    zipkin-autoconfigure-ui
    2.7.1

 启动类添加注解:

@EnableZipkinServer

其他服务模块应用,添加pom依赖:


    org.springframework.cloud
    spring-cloud-starter-zipkin
    1.3.3.RELEASE

添加配置信息:

#zipkin服务的地址
spring.zipkin.base-url= http://localhost:9000
spring.sleuth.sampler.percentage=1.0

 

Stream

消息驱动,有Sink、Source、Processor三种通道,特性有订阅发布、消费组、消息分区。

Bus

消息总线,配合Config仓库修改的一种Stream实现,

Sleuth

分布式服务追踪,需要搞清楚TraceID和SpanID以及抽样,如何与ELK整合。

Dashboard

Hystrix仪表盘,监控集群模式和单点模式,其中集群模式需要收集器Turbine配合。

Config

分布式配置中心,支持本地仓库、SVN、Git、Jar包内配置等模式,

未完待续

 

 

 

你可能感兴趣的:(开发总结)