springcloud

            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

springboot 是一种技术

springcloud 是一堆技术的解决方案

高扩展,高可用,高性能

服务选型

 约定>配置>编码

热部署devtools

1. 添加依赖与插件

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
                <addResources>true</addResources>
            </configuration>
        </plugin>
    </plugins>
</build>

  2. 设置

3. ctrl+shift+alt+/  ->  registry  勾选两项

 4.重启idea 即可,实现热部署,修改后,自动重新部署

http 访问方法

1. httpClient

2. RestTemplate

3. Feign

4. OpenFeign

RestTemplate

需要先配置bean,无法使用自动注入

@Configuration
public class ApplicationConfig {
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

调用上面的配置类,注入对象

@Resource
RestTemplate restTemplate;

post请求

ResponseEntity<ApiResult> apiResultResponseEntity = restTemplate.postForEntity(HOST + "/insert", payment, ApiResult.class);

get请求

ResponseEntity<ApiResult> forEntity = restTemplate.getForEntity(HOST + "/query?id="+id, ApiResult.class);

Eureka

提供服务的注册,组件包含了 Eureka Service(提供服务的注册) 和 Eureka Client(向服务中心进行访问)

@EnableEurekaServer 标识为 Eureka 服务端

@EnableEurekaClient 标识为 Eureka 客户端

服务注册流程

假设现在有 client、server、eurekaServer

client 会每隔一定周期去eurekaServer获取最新的 server 服务地址,缓存在本地,然后去直接调用server服务

配置 服务端


    <dependencies>
        <!--eureka-server-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
        <dependency>
            <groupId>com.nextstep</groupId>
            <artifactId>cloud-api-commons</artifactId>
        </dependency>
        <!--boot web actuator-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--一般通用配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>
server:
  port: 7001
eureka:
  instance:
    hostname: locathost #eureka服务端的实例名称
  client:
    #false表示不向注册中心注册自己。
    register-with-eureka: false
    #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    fetch-registry: false
    service-url:
      #设置与Eureka server交互的地址查询服务和注册服务都需要依赖这个地址。
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

最主要的就是@EnableEurekaServer

@SpringBootApplication
@EnableEurekaServer
public class CloudEurekaServer7001Application {

    public static void main(String[] args) {
        SpringApplication.run(CloudEurekaServer7001Application.class, args);
    }

}

配置 客户端

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
spring:
  application:
    name: cloud-payment-service
eureka:
  client:
    #表示是否将自己注册进Eurekaserver默认为true。
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetchRegistry: true
    service-url:
      defaultZone: http://localhost:7001/eureka

最主要的就是@EnableEurekaClient 

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

结果

Eureka 集群

互相注册,相互守望 

目的:高可用,注册集群的目的是为了实现负载均衡、故障容错


windwos 转发知识,所有的互联网请求,会首先匹配C:\Windows\System32\drivers\etc\hosts 目录中的内容,如果匹配上了, 就优先访问匹配内容,否则在去请求互联网DNS。

一共   2个eureka ,3个server,1个client

第一个eureka 配置

主要是defaultZone 配置其他的eureka服务,eureka服务端 通过defaultZone (多个用逗号隔开),来进行相互之间注册,相互之间调用,同时每个eureka,必须要注册除自己以外的其他所有eureka

server:
  port: 7001
eureka:
  instance:
    hostname: eureka-server #eureka服务端的实例名称
  client:
    #false表示不向注册中心注册自己。
    register-with-eureka: false
    #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    fetch-registry: false
    service-url:
      #设置与Eureka server交互的地址查询服务和注册服务都需要依赖这个地址。
      defaultZone: http://127.0.0.1:7002/eureka/

第二个eureka配置

server:
  port: 7002
eureka:
  instance:
    hostname: eureka-server #eureka服务端的实例名称
  client:
    #false表示不向注册中心注册自己。
    register-with-eureka: false
    #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    fetch-registry: false
    service-url:
      #设置与Eureka server交互的地址查询服务和注册服务都需要依赖这个地址。
      defaultZone: http://127.0.0.1:7001/eureka/

第一个server配置

server端,需要指定所有的 eureka 服务注册地址,这样才能在启动的时候,去所有的服务上进行注册,同时每个server 的启动端口或者ip ,不能两个都一致(例:127.0.0.1:8001 和 127.0.0.1:8002是符合要求的)

server:
  port: 8001
spring:
  application:
    name: cloud-payment-service
eureka:
  client:
    #表示是否将自己注册进Eurekaserver默认为true。
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetchRegistry: true
    service-url:
      defaultZone: http://127.0.0.1:7001/eureka,http://127.0.0.1:7002/eureka

 第二三个server配置

与第一个一致,就是自己的本服务端口或者ip ,不能同时一致

第一个client配置

eureka 的配置文件同上,spring.application.name 要改为client

同时,我们在client 访问 server的服务时,地址需要修改为server的 eureka 服务名称,例如cloud-payment-service 

private final String HOST = "http://CLOUD-PAYMENT-SERVICE";
@Resource
RestTemplate restTemplate;
@PostMapping("/order/payment/insert")
public ApiResult insert(@RequestBody Payment payment) {
    ResponseEntity<ApiResult> apiResultResponseEntity = restTemplate.postForEntity(HOST + "/insert", payment, ApiResult.class);
    ApiResult body = apiResultResponseEntity.getBody();
    return body;
}

其次,因为现在没有需要在 restTemplate 中设置负载均衡,需要在restTemplate 的bean上加上@LoadBalanced

@Configuration
public class ApplicationConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

最终效果,在client的 80端口访问 ,请求被转发到了serer的 8002 端口 

eureka 显示微服务信息

eureka:
  instance:
    instance-id: client
    prefer-ip-address: true #访问路径可以显示IP地址

结果对比

获取eureka 的服务注册信息

/**
 * 获取eureka 的服务注册信息
 * 需要在主启动类上添加 @EnableDiscoveryClient 注解
 * @return
 */
@GetMapping("/discovery")
public Object getDiscovery(){
    List<String> services = discoveryClient.getServices();
    for (int i = 0; i < services.size(); i++) {
        System.out.println("service:"+services.get(i));
    }
    List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
    for (ServiceInstance instance : instances) {
        System.out.println(instance.getServiceId()+instance.getHost());
    }
    return discoveryClient;
}
{
    "discoveryClients": [
        {
            "services": [
                "cloud-consumer-order",
                "cloud-payment-service"
            ],
            "order": 0
        },
        {
            "services": [],
            "order": 0
        }
    ],
    "services": [
        "cloud-consumer-order",
        "cloud-payment-service"
    ],
    "order": 0
}

Eureka 自我保护机制

rereka 当收不到微服务的心跳包的时候,默认情况下是不会立刻清除掉这个服务的,主要是为了防止误杀,保证了服务的高可用性,好死不如赖活着。

Consul

Downloads | Consul by HashiCorp

consul 安装

sudo yum install -y yum-utils

sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo

sudo yum -y install consul

consul 启动

cd /usr/bin

consul agent -dev    只能127.0.0.1可以访问

consul agent -dev  -client 0.0.0.0 -ui  指定ip可以访问

访问 Consul by HashiCorp http://47.98.231.255:8500 

consul 使用

         <!--SpringCloud consul-server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
server:
  port: 80
spring:
  application:
    name: cloud-consul-order
  cloud:
    consul:
      host: 47.98.231.255
      port: 8500
      discovery:
        #hostname: 127.0.0.1
        service-name: ${spring.application.name}
        heartbeat:
          enabled: true #心跳机制导致健康检查总是报红
@RestController
@Slf4j
public class OrderController {

    private final String HOST="http://cloud-consul-payment";

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/order/query")
    public ApiResult orderQuery(){
        ResponseEntity<ApiResult> forEntity = restTemplate.getForEntity(HOST + "/consul", ApiResult.class);
        return forEntity.getBody();
    }

}
@Configuration
public class ApplicationConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return  new RestTemplate();
    }
}
@SpringBootApplication
@EnableDiscoveryClient     //console,zookie 启动都需要该注解
public class CloudConsulOrder80Application {

    public static void main(String[] args) {
        SpringApplication.run(CloudConsulOrder80Application.class, args);
    }

}

三个注册中心的异同点


 
CAP:

C:Consistency (强一致性)

A:Availability (可用性)

P:Partition tolerance (分区容错性)

最多只能同时较好的满足两个。

CAP理论的核心是:一个分布式系统不可能同时很好的满足一致性,可用性和分区容错性这三个需求。

因此,根据CAP原理将NoSQL数据库分成了满足CA原则、满足CP原则和满足AP原则三大类:

CA - 单点集群,满足—致性,可用性的系统,通常在可扩展性上不太强大。
CP - 满足一致性,分区容忍必的系统,通常性能不是特别高。
AP - 满足可用性,分区容忍性的系统,通常可能对一致性要求低一些。

Ribbon

Eureka 自带 Ribbon

客户端 负载均衡 和 调用的工具

负载均衡:集中式(作用在服务端Nginx) , 进程内(作用在客户端Ribbon)

IRule 自带的默认访问规则

IRule 的负载均衡规则不能放在 CompentScan 下 ,如果放在CompentScan下会被Spring加载到,那么所有的Ribbon的客户端都能够使用到,所以无法达到特殊定制的目的。又因为我们@SpringBootApplication 注解中自带@CompentScan ,所以负载均衡规则,不能够放在spring启动类同级及子级目录。

不知道怎么,不能在Consul 上调用,暂时先跳过不学

代码实现

@SpringBootApplication 目录之外 新建IRuleConfig

package com.nextstep.irule;
@Configuration
public class IRuleConfig {
    @Bean
    public IRule getIRule(){
        return new RandomRule();
    }
}
启动类上增加
@RibbonClient(name = "CLOUD-CONSUL-PAYMENT",configuration = IRuleConfig.class)

OpenFeign

openFeign底层使用的就是Ribbon,所以有时候需要配置Ribbon

声明式web客户端服务,让客户端调用变得更加容易,只需创建一个接口,增加注解即可   

@FeignClient(value = "consul 服务名称 例如:cloud-consul-order")
        <!--openfeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--SpringCloud consul-server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
server:
  port: 80
spring:
  application:
    name: cloud-openfeign-order
  cloud:
    consul:
      host: 47.98.231.255
      port: 8500
      discovery:
        service-name: ${spring.application.name}
        heartbeat:
          enabled: true #心跳机制导致健康检查总是报红
      config:
        enabled: true
@SpringBootApplication
@EnableFeignClients // feign 注解
@EnableDiscoveryClient  // consule 注解
public class CloudOpenfeignOrder80Application {
    public static void main(String[] args) {
        SpringApplication.run(CloudOpenfeignOrder80Application.class, args);
    }
}
@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;
    @GetMapping("/order/query")
    public ApiResult orderQuery(){
        ApiResult consul = orderService.consul();
        return consul;
    }
}
@Component
@FeignClient(value = "cloud-consul-payment")
public interface OrderService {
    @GetMapping("/consul")
    ApiResult consul();
}

openFeign超时

默认 访问资源时间限制 1秒钟

修改时间限制:

server:
  port: 80
spring:
  application:
    name: cloud-openfeign-order
  cloud:
    consul:
      host: 47.98.231.255
      port: 8500
      discovery:
        service-name: ${spring.application.name}
        heartbeat:
          enabled: true #心跳机制导致健康检查总是报红
      config:
        enabled: true
# 设置openFeign 超时时间,默认1s
ribbon:
  ReadTimeout: 5000 #建立连接超时时间
  ConnectTimeout: 5000  #访问超时时间

openFeign 日志

server:
  port: 80
spring:
  application:
    name: cloud-openfeign-order
  cloud:
    consul:
      host: 47.98.231.255
      port: 8500
      discovery:
        service-name: ${spring.application.name}
        heartbeat:
          enabled: true #心跳机制导致健康检查总是报红
      config:
        enabled: true
# 设置openFeign 超时时间,默认1s
ribbon:
  ReadTimeout: 5000 #建立连接超时时间
  ConnectTimeout: 5000  #访问超时时间

logging:
  level:
    #openFeign 日志监控那个接口,且其级别(接口的全类名: 正常日志的级别)
    com.nextstep.cloudopenfeignorder80.service.OrderService: debug
@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feignLoggerLevel(){
        /**
         * NONE:默认的,不显示任何日志;
         * BASIC:仅记录请求方法、URL、响应状态码及执行时间;
         * HEADERS:除了BASIC中定义的信息之外,还有请求和响应的头信息;
         * FULL:除了HEADERS中定义的信息之外,还有请求和响应的正文及元数据。
         */
        return Logger.Level.FULL;
    }
}

Hystrix(服务降级)

处理分布式系统延迟和容错的开源库

能够保证当一个服务出现问题的时候,不会影响到整个的服务,从而保证了分布式系统的弹性。

服务降级,服务熔断,服务实时监控,限流,隔离

导致降级原因:程序运行异常、超时、服务熔断

插播知识点

正向代理(代理):我委托第三方去访问服务器,服务器并不知道是我访问的,第三方将结果原封不动的给我返回。

反向代理:服务器存在多台,我访问第三方,第三方根据实际情况,将我的请求发送到合适的服务器,此时我并不知道,我到底正真请求的是那一台服务器。

Gateway 网关

gateway 三大概念:route(路由)、predicate(断言)、filter(过滤)

gateway 工作流程:路由转发、执行过滤链

基于webflux 框架,异步非阻塞,主要用于反向代理、熔断、安全、流量监控、限流

1. 简单实现(网关路由配置)yaml配置实现

<dependencies>
        <!--gateway-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <!--SpringCloud consul-server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
        <dependency>
            <groupId>com.nextstep</groupId>
            <artifactId>cloud-api-commons</artifactId>
        </dependency>
        <!--一般基础配置类-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  #############################新增网关配置###########################
  cloud:
    gateway:
      routes:
        - id: payment_routh #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://127.0.0.1:8006          #匹配后提供服务的路由地址
          #uri: lb://cloud-payment-service #匹配后提供服务的路由地址
          predicates:
            - Path=/consul         # 断言,路径相匹配的进行路由(可用**通配符匹配)

        - id: payment_routh2 #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://127.0.0.1:8006          #匹配后提供服务的路由地址
          #uri: lb://cloud-payment-service #匹配后提供服务的路由地址
          predicates:
            - Path=/consul/query         # 断言,路径相匹配的进行路由

    consul:
      host: 47.98.231.255
      port: 8500
      discovery:
        #hostname: 127.0.0.1
        service-name: ${spring.application.name}
        heartbeat:
          enabled: true #心跳机制导致健康检查总是报红
@SpringBootApplication
@EnableDiscoveryClient
public class CloudGatewayGateway9527Application {
    public static void main(String[] args) {
        SpringApplication.run(CloudGatewayGateway9527Application.class, args);
    }
}

那么,我们访问网关 http://127.0.0.1:9527/consul/query 的时候就会转发到 8006的/consul/query

2. 动态路由(通过服务名调用)

spring:
  application:
    name: cloud-gateway
  #############################新增网关配置###########################
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:
        - id: payment_routh #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          #uri: http://127.0.0.1:8006          #匹配后提供服务的路由地址
          #第一种:ws(websocket)方式: uri: ws://localhost:9000
          #第二种:http方式: uri: http://localhost:8130/
          #第三种:lb(注册中心中服务名字)方式: uri: lb://brilliance-consumer
          uri: lb://cloud-consul-payment #匹配后提供服务的路由地址
          predicates:
            - Path=/consul         # 断言,路径相匹配的进行路由

        - id: payment_routh2 #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          #uri: http://127.0.0.1:8006          #匹配后提供服务的路由地址
          uri: lb://cloud-consul-payment #匹配后提供服务的路由地址
          predicates:
            - Path=/consul/query         # 断言,路径相匹配的进行路由

predicate(断言)

常用的Route Predicate Factory

The After Route Predicate Factory
The Before Route Predicate Factory
The Between Route Predicate Factory
The Cookie Route Predicate Factory
The Header Route Predicate Factory
The Host Route Predicate Factory
The Method Route Predicate Factory
The Path Route Predicate Factory
The Query Route Predicate Factory
The RemoteAddr Route Predicate Factory
The weight Route Predicate Factory

  cloud:
    gateway:
      discovery:
        locator:
          enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:
        - id: payment_routh #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          #uri: http://127.0.0.1:8006          #匹配后提供服务的路由地址
          #第一种:ws(websocket)方式: uri: ws://localhost:9000
          #第二种:http方式: uri: http://localhost:8130/
          #第三种:lb(注册中心中服务名字)方式: uri: lb://brilliance-consumer
          uri: lb://cloud-consul-payment #匹配后提供服务的路由地址
          predicates:
            - Path=/consul         # 断言,路径相匹配的进行路由
            # 这个时间后才能起效才能访问
            - After=2017-01-20T17:42:47.789-07:00[America/Denver]
            # 两个时间点之间才能访问
            - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
            # 携带cookie 名称为 chocolate 值为 ch.p (正则匹配)才能访问
            # curl http://localhost:9527/payment/lb --cookie "chocolate=chip"
            - Cookie=chocolate, ch.p
            # 携带Header 名称为 X-Request-Id 值为 正整数 (正则匹配)才能访问、
            # curl http://localhost:9527/payment/lb -H "X-Request-Id:123"
            - Header=X-Request-Id, \d+

spring cloud alibaba

nacos

 从官网下载nacos  并部署到服务器 

cd /nacos/bin

sh startup.sh -m standalone

nacos 支持 cp 和 ap 模式,可以随意切换

nacos依赖

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>2.1.0.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!--SpringCloud ailibaba nacos 服务注册依赖 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
         <!--nacos-config  nacos 配置依赖-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

服务注册 

server:
  port: 9002
spring:
  application:
    name: cloud-alibaba-nacos-payment
  cloud:
    nacos:
      discovery:
        server-addr: 47.98.231.255:8848 #配置Nacos地址
  management:
    endpoints:
      web:
        exposure:
          include: '*'
@SpringBootApplication
@EnableDiscoveryClient //nacos 注解
public class CloudAlibabaNacosPayment9002Application {
    public static void main(String[] args) {
        SpringApplication.run(CloudAlibabaNacosPayment9002Application.class, args);
    }
}

服务启动后,去nacos 官网就可以看到注册的服务

服务配置

springboot 配置文件加载顺序,先 bootstrap 在application。首先我们的项目启动,要先保证现有共性,在去初始化个性,所以我们在 bootstrap 中加载 nacos 配置,在application 中加载 个性配置,这样application 就会覆盖bootstrap 中的配置,即可达到,现有共性再有个性的效果。

1.本地配置

application.yaml

server:
  port: 9003
spring:
  application:
    name: cloud-alibaba-nacos-config

bootstrap.yaml

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 47.98.231.255:8848 #Nacos服务注册中心地址
      config:
        server-addr: 47.98.231.255:8848 #Nacos作为配置中心地址
        file-extension: yaml #指定yaml格式的配置
        #group: DEV_GROUP
        #namespace: 7d8f0f5a-6a53-4785-9686-dd460158e5d4

启动类上加注解 

@EnableDiscoveryClient

服务类

@RefreshScope作用: application.properties里自定义的变量也能通过@Value 注解正常注入,同时,让nacaos 能够实时修改value值

@RestController
@Slf4j
@RefreshScope //支持Nacos的动态刷新功能。 仅限于当前类
public class ConfigController {
    @Value("${nacos.config.application.name:}")
    String applicationName;
    @GetMapping("/getValue")
    public String getValue(){
        return applicationName;
    }
}

2. nacos 上的配置文件名格式 

3. nacos 配置

cloud-alibaba-nacos-config.yaml

nacos:
    config:
        application:
            name: aaaaaaaaaaa

综上,就能够实时的读取到nacos 的配置



多环境配置

DataId 规则,见上面的   2. nacos 上的配置文件名格式 

且需要在当前微服务配置中指明,读取的 group 和 namespace

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 47.98.231.255:8848 #Nacos服务注册中心地址
      config:
        server-addr: 47.98.231.255:8848 #Nacos作为配置中心地址
        file-extension: yaml #指定yaml格式的配置
        group: admin
        namespace: 0ca77fc9-86a2-493c-b96f-1fa558c678c2

nginx

 负载均衡

动静分离

反向代理

集群

高性能的http 反向代理服务器程序,占用内存少。

理论理解

1.正向代理

用户无法直接访问 服务,需要通过第三方的代理服务器才能访问,此时用户配置第三方代理服务器,通过代理服务器去访问 服务,并返回。此时,用户知道自己真正访问的服务。

 2.反向代理

相对于用户而言,是不知道有没有反向代理的存在,客户端不需要进行任何配置,客户端发送请求到反向代理服务器,由反向代理服务器来选择去那个真是服务器获取数据,并返回。这样做只暴露了代理服务器,隐藏了真实的服务器。

 3. 负载均衡

增加服务器的数量,根据 各个服务器的实际处理请求情况,将请求分发到某个服务器进行处理,从而达到负载均衡的效果。

 4. 动静分离

为了加快网站解析速度,可以把动态页面和静态页面由不同的服务器解析,加快访问速度,降低原来单一服务器的压力。

nginx 安装

安装相关依赖

yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel

下载nginx 

wget http://nginx.org/download/nginx-1.18.0.tar.gz

解压nginx 进入到nginx-1.18.0 目录

1. 检查安装文件 例如gc等等

不安装ssl命令:./configure

安装ssl命令:./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module

2.编译安装文件

make

3.安装

make install

此时在 /usr/local/目录下会创建一个 nginx 目录

4.启动

cd /usr/local/nginx/sbin

./nginx

或者  直接执行/usr/local/nginx/sbin/nginx

5.访问

ip:80  (nginx 默认端口80)

nginx 常用命令

1. 启动nginx 

./nginx    (不是 sh nginx)

或者  直接执行/usr/local/nginx/sbin/nginx

2. 查看版本

./nginx -v

3.关闭nginx

./nginx -s stop

4. 重新加载 nginx配置文件 (修改了配置后,不想重启nginx )

./nginx -s reload

nginx 配置

vi conf/nginx.conf

第一部分 全局块

主要用来配置nginx 服务器的整体运行指令

例如:worker_processes 1;   #值越大,处理的并发量也就越大

 第二部分 events块()

用来配置 nginx服务器与用户网络的连接

例如:worker_connections  1024; #表示支持最大连接数

第三部分 http块

包含 http 全局块 、server块

1. 反向代理实操

1. 一个项目的反向代理

监听80 端口,当访问 47.98.231.255时(47.98.231.255:80不生效),将请求转发到127.0.0.1:8080端口去

 server {
        listen       80; #nginx监听端口
        server_name  47.98.231.255; #nginx监听地址

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            proxy_pass http://127.0.0.1:8080; #访问47.98.231.255:80 端口转发路径
            index  index.html index.htm;
        }
}

2. 多个项目的反向代理

当访问8000 端口时,根据正则匹配访问的路径,将请求转发到对应的服务上去。那么当访问http://47.98.231.255:8000/request8081/index.html 时,则实际访问路径为 http://127.0.0.1:8081/request8081/index.html

server {
        listen       8000;
        server_name  47.98.231.255;

        # ~ 代表模糊匹配

        # /xx/  表示域名后面直接是匹配字符

        # proxy_pass 结尾有/ 代表最终访问地址不会携带 location 匹配字符串

        location ~ /request8080/ {
            root   html;
            proxy_pass http://127.0.0.1:8080;
            index  index.html index.htm;
        }

        location ~ /request8081/ {
                proxy_pass http://127.0.0.1:8081/;
        }
    }

多个项目正则匹配时,通过location ~ 后面的正则表达式来进行匹配

2. 负载均衡实操

1. 负载均衡

首先定义了一个组(tomcat_test_server ),将服务放在组中,然后通过访问组的方式,根据规则,访问某一个服务
    upstream tomcat_test_server {
        server 127.0.0.1:8080;
        server 127.0.0.1:8081;
    }

    server {
        listen 8001;
        server_name 47.98.231.255;

        location / {
                proxy_pass http://tomcat_test_server;
        }

    }
2. 负载均衡规则

1. 轮询(默认)

将请求按照时间顺序,逐一分配到不同的服务器上,当某个服务down掉时,自动剔除

upstream tomcat_test_server {
        server 127.0.0.1:8080;
        server 127.0.0.1:8081;
}

2. weight 权重

权重越高,分配的客户端越多

upstream tomcat_test_server {
        server 127.0.0.1:8080 weight=8;
        server 127.0.0.1:8081 weight=3;
}

3. ip_hash

每个客户端分配唯一一个固定的后端服务器进行访问,如果没有单点登录情况下,可以避免session的共享问题

upstream tomcat_test_server {
        ip_hash;
        server 127.0.0.1:8080;
        server 127.0.0.1:8081;
}

4. fair

根据每个服务响应的速度时间,来进行请求的分配,响应时间越快,优先级越高

upstream tomcat_test_server {
        server 127.0.0.1:8080;
        server 127.0.0.1:8081;
        fair;
}

3.vue项目部署linux

配置文件中添加server

        location / {
            root   /usr/local/one-family/one-family-manage-web/;
            try_files $uri $uri/ /index.html;
        }

nginx重新读取配置文件 ./nginx -s reload

4. 同源策略(多个项目)

比如   www.baidu.com 指向一个项目,www.baidu.com/shop  指向一个项目

server {
        listen       8039;
        server_name  localhost;
        add_header Access-Control-Allow-Origin *;

        location /shop {
          alias  /usr/local/one-family-test/one-family-shop-web;
          index  index.html index.htm;
          try_files $uri $uri/ @router; # 需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
        }
        location @router {
          rewrite ^.*$ /shop/index.html last;

        }
    }
 

    server {
        listen 80 ;
        listen 443 ssl;
        server_name  localhost;

        location / {
            root   /usr/local/one-family-test/one-family-manage-web/;
            try_files $uri $uri/ /index.html;
        }

        location /shop/{
            proxy_pass http://localhost:8039/shop/;
        }

}

4. ssl证书安装

前往https://yundunnext.console.aliyun.com/?p=casnext#/certExtend/free 申请  DigiCert 免费版 SSL 证书,并下载 nginx版本

vim {{nginx安装目录}} /config/nginx.conf

编辑如下配置

    server {
        # 可支持监听多个端口
        listen 80 ;
        listen   443 ssl;
        server_name  localhost;

        #ssl on;
        #证书位置
        ssl_certificate /usr/local/nginx/key_book_file_dir/www.saas-test.one-more.cn.pem;
        ssl_certificate_key /usr/local/nginx/key_book_file_dir/www.saas-test.one-more.cn.key;
        ssl_session_timeout 5m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
        ssl_prefer_server_ciphers on;
     }

nginx -t 测试,此时因为nginx 没有安装ssl配置,报错 。按照如下操作:

http://t.zoukankan.com/victorcode-p-10901322.html

nginx -t  重新测试

需要注意的是:申请证书时的域名,应该与解析时的保持一致。

错误的例子就是解析的第二条

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud是一个用于构建分布式系统的开发工具集合。它提供了一些常用的组件和框架,包括服务注册和发现、负载均衡、断路器、分布式配置等等。在使用Spring Cloud时,有一些常见的错误和注意事项需要注意。 首先,关于Spring Boot和Spring Cloud版本对应错误。在使用Spring Cloud时,需要确保Spring Boot和Spring Cloud的版本兼容。不同版本之间可能存在依赖冲突或不兼容的情况,因此需要根据官方文档或者相关文档来选择合适的版本。 另外,Spring Cloud Config是一个用于集中管理和动态获取配置的工具。它支持从Git、SVN或本地文件系统中获取配置文件,并提供了服务器和客户端支持。你可以通过官方使用说明文档了解更多关于Spring Cloud Config的详细信息。 此外,关于选择使用Nacos还是Eureka作为服务注册和发现组件的问题。Nacos是一个功能更强大的服务注册和发现组件,它整合了Spring Cloud Eureka、Spring Cloud Config和Spring Cloud Bus的功能。使用Nacos可以实现配置的中心动态刷新,而不需要为配置中心新增集群或使用消息队列。另一方面,Eureka是Spring Cloud原生全家桶的一部分,相对来说更加稳定一些。选择使用哪个组件需要根据具体的需求和项目特点来决定。 综上所述,Spring Cloud是一个用于构建分布式系统的开发工具集合,它提供了一些常用的组件和框架。在使用Spring Cloud时,需要注意Spring Boot和Spring Cloud版本的兼容性,并可以使用Spring Cloud Config来动态获取配置。同时,可以选择使用Nacos或Eureka作为服务注册和发现组件,具体选择需要根据项目需求来决定。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值