Spring Cloud / Alibaba 微服务架构

这是我参与11月更文挑战的第19天,活动详情查看:2021最后一次更文挑战

上篇文章给大家介绍了SpringCloud Gateway 的工作模型及请求进入到我们的SpringCloud Gateway后,最终到达Proxied Service 目标服务经过的四个阶段,本篇文章将介绍一下Predicate(谓词/断言)的原理与应用。

谓词 Predicate 的原理与应用

之前的文章中有介绍过Predicate,它是Gateway的三大组成部分之一,是对条件匹配的判断。

谓词Predicate是什么

认识Predicate

由Java8引入,位于java.util.function包中,是一个FunctionalInterface,即函数式接口。它只有一个test方法没有实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
java复制代码@FunctionalInterface
public interface Predicate<T> {

/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
...
}

可以看到,test方法需要输入一个参数,返回boolean类型,通常用在stream的filter中,表示是否满足过滤条件

我们先创建一个网关子模块,在里面写一些例子的测试代码让我们熟悉Predicate的方法,介绍Predicate的应用方法和应用过程。

创建网关子模块(e-commerce-gateway)来编写例子

1、创建子模块、修改pom文件等步骤不再赘述。

此处有一点需要注意,e-commerce-gateway之所以不像其他子模块一样在依赖里引入e-commerce-mvc-config,是因为我们的e-commerce-mvc-config依赖了starter-web,starter-web里依赖了starter-tomcat,它是由web去引用进来的。gateway子模块使用的是WebFlux,默认使用的是Netty,所以我们需要从依赖中排除tomcat相关的依赖,所以不能引入spring-boot-starter-web这个依赖。

2、resources下创建配置类bootstrap.yml

3、创建启动类

1
2
3
4
5
6
7
8
9
10
11
12
less复制代码/**
* <h1>网关启动入口</h1>
* */
@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {

public static void main(String[] args) {

SpringApplication.run(GatewayApplication.class, args);
}
}

4、创建测试类验证工程搭建正确性

image.png

Java8 Predicate test方法使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
less复制代码/**
* <h1>Java8 Predicate 使用方法与思想</h1>
* */
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class PredicateTest {

public static List<String> MICRO_SERVICE = Arrays.asList(
"nacos", "authority", "gateway", "ribbon", "feign", "hystrix", "e-commerce"
);

/**
* <h2>test 方法主要用于参数符不符合规则, 返回值是 boolean</h2>
* */
@Test
public void testPredicateTest() {

Predicate<String> letterLengthLimit = s -> s.length() > 5;
MICRO_SERVICE.stream().filter(letterLengthLimit).forEach(System.out::println);
}
}

test 方法主要用于判断参数符不符合规则, 返回值是 boolean。

上图代码指的是依次输出MICRO_SERVICE中字符串长度大于5的。

下篇文章我们将介绍一下Predicate中and、negate、or、isEqual方法。

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%