微服务之nacos、feign、gateway

nacos

简介

  1. 为什么叫Nacos:前四个字母分别为Naming和Configuration的前两个字母,最后的s为Service。

  2. 是什么:一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。

  3. Nacos: Dynamic Naming and Configuration Service
    Nacos就是注册中心+配置中心的组合 -> Nacos = Eureka+Config+Bus

  4. 能干嘛
    替代Eureka做服务注册中心
    替代Config做服务配置中心

  5. 下载:https://github.com/alibaba/nacos/releases
    文档:https://spring-cloud-alibaba-group.github.io/github-pages/greenwich/spring-cloud-alibaba.html

配置

父pom

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

pom

  1. 服务发现
<!--SpringCloud ailibaba nacos-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
  1. 配置中心
<!--nacos-config-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

yaml

注意:每个服务必须指定名字!否则无法服务发现

  • bootstrap.yml
spring:
  cloud:
     nacos:
      discovery:
        server-addr: localhost:8848 #Nacos服务注册中心地址
      config:
        server-addr: localhost:8848 #Nacos作为配置中心地址
        file-extension: yaml #指定yaml格式的配置
        group: DEV_GROUP
        namespace: 7d8f0f5a-6a53-4785-9686-dd460158e5d4 #命名空间
  • application.yml
spring:
  profiles:
    active: dev # 表示开发环境
    #active: test # 表示测试环境
    #active: info

以上配置解释:

在 Nacos Spring Cloud中,dataId的完整格式如下:
${prefix}-${spring-profile.active}.${file-extension}

其中:

  • prefix默认为spring.application.name的值,也可以通过配置项spring.cloud.nacos.config.prefix来配置。
  • spring.profile.active即为当前环境对应的 profile。注意:当spring.profile.active为空时,对应的连接符 - 也将不存在,datald 的拼接格式变成${prefix}.${file-extension}
  • file-exetension为配置内容的数据格式,可以通过配置项spring .cloud.nacos.config.file-extension来配置。目前只支持properties和yaml类型。

最后公式:
${spring.application.name)}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
例如上面的配置:应用名-dev.yaml

main

@EnableDiscoveryClient

不加这个也可以

@RefreshScope

  • @Value需要动态获取值,要加Spring Cloud 原生注解@RefreshScope实现配置自动更新。
  1. 需要动态获取值的地方加@RefreshScope注解
    在这里插入图片描述
  2. nacos的初始配置:
    在这里插入图片描述启动项目,访问,取到的值:
    在这里插入图片描述
  3. 不重启项目的情况下修改nacos的配置:
    在这里插入图片描述
    再次访问,发现取到的数据也改变了:(必须加@RefreshScope注解)
    在这里插入图片描述

持久化

  1. 安装数据库,版本要求:5.6.5+
  2. 初始化mysq数据库,数据库初始化文件: nacos-mysql.sql
  3. 修改conf/application.properties文件(增加支持mysql数据源配置(目前只支持mysql),添加mysql数据源的url、用户名和密码):
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://localhost:3306/nacos_devtest?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=nacos_devtest
db.password=youdontknow

使用

  • 新建命名空间,添加如下配置,并把原来在application.yaml中的内容分别写到以下文件中:
    在这里插入图片描述

    注:我的命名空间id可以自定义:而不是uuid在这里插入图片描述

  • 配置bootstrap.yaml:
spring:
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        namespace: coupon #写命名空间ID
        extension-configs:
          - dataid: datasource.yaml
            refresh: true
            group: dev
          - dataid: mybatis.yaml
            refresh: true
            group: dev
          - dataid: other.yaml
            refresh: true
            group: dev

启动时候的部分日志:读取了上面配置的文件
在这里插入图片描述

  • nacos做配置中心
    在这里插入图片描述
    在这里插入图片描述

feign

面向接口编程

配置

pom

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

main

@EnableFeignClients

service

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;

@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")//微服务的服务名
public interface PaymentFeignService{
    //对应微服务的controller中包含的方法

}

超时

  • 解决方法:在yaml中配置如下内容:(时间自己看着改,例如,read time out,就把readTimeout时间改大一些)
feign:
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000
  hystrix:
    enabled: true

hystrix:
  command:
    default:
      execution:
        timeout:
          enabled: true
        isolation:
          thread:
            timeoutInMilliseconds: 60000

使用

两个微服务使用的对象可以不一致:

在这里插入图片描述
在这里插入图片描述

远程调用未携带Cookie等参数问题

在这里插入图片描述

发现Feign直接新建一个请求
在这里插入图片描述
这个新请求没有headers信息:
在这里插入图片描述
继续往下看,有这么一个方法:
在这里插入图片描述
它遍历了该类的所有拦截器对请求进行处理,默认拦截器是个空的List
在这里插入图片描述
拦截器的类型是:
在这里插入图片描述
我们可以自定义一个拦截器处理我们自己的请求,使其加上Cookie,例如:

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @program: gulimall
 * @description: feign拦截器
 * @author: liangjiayy
 * @create: 2022-06-22 10:26
 **/
@Configuration
public class MyFeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        String cookie = ((ServletRequestAttributes) requestAttributes).getRequest().getHeader("Cookie");
        template.header("Cookie",cookie);
    }
}

其中,RequestContextHolder.getRequestAttributes()主要利用ThreadLocal实现,当前线程共享,可以获取到当前请求信息
在这里插入图片描述

这样,会自动为我们加上Cookie信息,如图:
在这里插入图片描述
如果RequestContextHolder.getRequestAttributes()获取到的为null,可在拦截器(HandlerInterceptor的preHandle()方法)加入以下代码:

RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
RequestContextHolder.setRequestAttributes(requestAttributes,true);

gateway

官网: https://docs.spring.io/spring-cloud-gateway/docs/2.2.9.RELEASE/reference/html/

三大核心概念

  1. Route(路由) - 路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如断言为true则匹配该路由;
  2. Predicate(断言) - 参考的是Java8的java.util.function.Predicate,开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由;查看可配置的断言
  3. Filter(过滤) - 指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改。查看可配置的过滤器
    在这里插入图片描述

配置

pom

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

yml配置样例

spring:
  cloud:
    gateway:
      routes:
        - id: payment_routh #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8001          #匹配后提供服务的路由地址
          #uri: lb://cloud-payment-service #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/get/**         # 断言,路径相匹配的进行路由

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

*配置方式2:

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GateWayConfig
{
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder)
    {
        RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();

        routes.route("path_route_atguigu",
                r -> r.path("/guonei")
                        .uri("http://news.baidu.com/guonei")).build();

        return routes.build();
    }
}

配置说明

After

- After=2017-01-20T17:42:47.789-07:00[America/Denver]

在某个时间之后的请求才会被转发

Before

- Before=2017-01-20T17:42:47.789-07:00[America/Denver]

在某个时间之前的请求才会被转发

Between

- Between=2017-01-20T17:42:47.789-07:00[America/Denver],2017-01-21T17:42:47.789-07:00[America/Denver]

在某个时间段之间的才会被转发

Cookie

- Cookie=mycookie,mycookievalue

cookie中包含mycookie=mycookievalue

Path

- Path=/gate/,/rule/

当请求的路径为gate、rule开头的时,转发到http://localhost:9023服务器上

Header

- Header=X-Request-Id, \d+

携带参数X-Request-Id且满足\d+正则表达式的请求头才会匹配

Host

- Host=**.somehost.org,**.anotherhost.org

www.somehost.org 、beta.somehost.org 、www.anotherhost.org.都可以被匹配到

Method

- Method=GET,POST

get、put请求都可以访问

Path

- Path=/red/{segment},/blue/{segment}

/red/1 、/red/blue 、 /blue/green都可以

Query

- Query=red, gree

请求参数中包含red=gree键值对,例如:http://xx?red=gree

RemoteAddr

- RemoteAddr=192.168.1.1/24

IP地址或IP段

Weight

spring:
  cloud:
    gateway:
      routes:
      - id: weight_high
        uri: https://weighthigh.org
        predicates:
        - Weight=group1, 8
      - id: weight_low
        uri: https://weightlow.org
        predicates:
        - Weight=group1, 2
  

80%概率去访问 weighthigh.org , 20%概率去访问 weighlow.org

路径改写之RewritePath

spring:
  cloud:
    gateway:
      routes:
      - id: rewritepath_route
        uri: https://example.org
        predicates:
        - Path=/red/**
        filters:
        - RewritePath=/red(?<segment>/?.*), $\{segment}

访问 /red/blue 会跳转到 /blue

附录

IDEA中设置Run Dashboard

在另一篇文章中:https://blog.csdn.net/m0_55155505/article/details/124164365

设置最大运行内存

-Xmx用来设置你的应用程序(不是JVM)能够使用的最大内存数:
虚拟机选项中设置:-Xmx100m , 表示最多只能用100M
在这里插入图片描述

批量启动微服务:

  • 编辑配置
    在这里插入图片描述
  • +, 找到compound
    在这里插入图片描述
  • 通过+来添加需要批量启动的配置,写上名称,应用即可
    在这里插入图片描述
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值