reactor.util.context.Context类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(8.2k)|赞(0)|评价(0)|浏览(625)

本文整理了Java中reactor.util.context.Context类的一些代码示例,展示了Context类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Context类的具体详情如下:
包路径:reactor.util.context.Context
类名称:Context

Context介绍

[英]A key/value store that is propagated between components such as operators via the context protocol. Contexts are ideal to transport orthogonal information such as tracing or security tokens.

Context implementations are thread-safe and immutable: mutative operations like #put(Object,Object) will in fact return a new Context instance.

Note that contexts are optimized for low cardinality key/value storage, and a user might want to associate a dedicated mutable structure to a single key to represent his own context instead of using multiple #put, which could be more costly. Past five user key/value pair, the Context will use a copy-on-write implementation backed by a new java.util.Map on each #put.
[中]通过上下文协议在组件(如运算符)之间传播的键/值存储。上下文非常适合传输正交信息,如跟踪或安全令牌。
上下文实现是线程安全且不可变的:像#put(Object,Object)这样的变异操作实际上将返回一个新的上下文实例。
请注意,上下文针对低基数键/值存储进行了优化,用户可能希望将专用可变结构与单个键关联以表示自己的上下文,而不是使用多个#put,这可能会更昂贵。在过去的五个用户密钥/值对中,上下文将使用一个由新java支持的写时拷贝实现。util。在每一张桌子上画一张地图。

代码示例

代码示例来源:origin: reactor/reactor-core

/**
 * Resolve a value given a key within the {@link Context}.
 *
 * @param key a lookup key to resolve the value within the context
 *
 * @return an {@link Optional} of the value for that key.
 */
default <T> Optional<T> getOrEmpty(Object key){
  if(hasKey(key)) {
    return Optional.of(get(key));
  }
  return Optional.empty();
}

代码示例来源:origin: reactor/reactor-core

@Override
public Context delete(Object key) {
  Objects.requireNonNull(key, "key");
  if (this.key.equals(key)) {
    return Context.empty();
  }
  return this;
}

代码示例来源:origin: spring-projects/spring-security

/**
 * Creates a Reactor {@link Context} that contains the {@code Mono<SecurityContext>}
 * that can be merged into another {@link Context}
 * @param securityContext the {@code Mono<SecurityContext>} to set in the returned
 * Reactor {@link Context}
 * @return a Reactor {@link Context} that contains the {@code Mono<SecurityContext>}
 */
public static Context withSecurityContext(Mono<? extends SecurityContext> securityContext) {
  return Context.of(SECURITY_CONTEXT_KEY, securityContext);
}

代码示例来源:origin: reactor/reactor-core

@Override
public StepVerifier.ContextExpectations<T> containsAllOf(Context other) {
  this.contextExpectations = this.contextExpectations.andThen(c -> {
    boolean all = other.stream().allMatch(e -> e.getValue().equals(c.getOrDefault(e.getKey(), null)));
    if (!all) {
      throw errorFormatter.assertionError(String.format("Expected Context %s to contain all of %s", c, other));
    }
  });
  return this;
}

代码示例来源:origin: reactor/reactor-core

@Override
  public Context currentContext() {
    return Context.empty()
           .put("test", "baseSubscriber");
  }
});

代码示例来源:origin: reactor/reactor-core

@Test
public void currentContext() throws InterruptedException {
  StepVerifier.create(Mono.just("foo")
              .flatMap(d -> Mono.subscriberContext()
                       .map(c -> d + c.get(Integer.class)))
              .subscriberContext(ctx ->
                  ctx.put(Integer.class, ctx.get(Integer.class) + 1))
              .flatMapMany(Mono::just)
              .subscriberContext(ctx -> ctx.put(Integer.class, 0)))
        .expectNext("foo1")
        .verifyComplete();
}

代码示例来源:origin: reactor/reactor-core

@Test
public void monoSubscriberContextWithMergedEmpty() {
  StepVerifier.create(
      Mono.just("foo")
        .flatMap(v -> Mono.subscriberContext())
        .subscriberContext(Context.empty())
        .subscriberContext(Context.of("initial", "value"))
  )
        .expectNextMatches(c -> c.hasKey("initial"))
        .verifyComplete();
}

代码示例来源:origin: reactor/reactor-core

@Test
public void monoSubscriberContextPutsAll() {
  StepVerifier.create(
      Mono.just("foo")
        .flatMap(v -> Mono.subscriberContext())
        .subscriberContext(Context.of("foo", "bar", 1, "baz"))
        .subscriberContext(Context.of("initial", "value"))
  )
        .expectNextMatches(c -> c.hasKey("foo") && c.hasKey(1) && c.hasKey("initial"))
        .verifyComplete();
}

代码示例来源:origin: reactor/reactor-core

@Test
public void putDifferentKeyContextN() throws Exception {
  Context put = c.put(7, "Abis");
  assertThat(put)
      .isInstanceOf(ContextN.class);
  assertThat(put.stream().map(Map.Entry::getKey))
      .containsExactly(1, 2, 3, 4, 5, 6, 7);
  assertThat(put.stream().map(Map.Entry::getValue))
      .containsExactly("A", "B", "C", "D", "E", "F", "Abis");
}

代码示例来源:origin: reactor/reactor-core

@Override
public StepVerifier.ContextExpectations<T> hasKey(Object key) {
  this.contextExpectations = this.contextExpectations.andThen(c -> {
      if (!c.hasKey(key))
        throw errorFormatter.assertionError(String.format("Key %s not found in Context %s", key, c));
  });
  return this;
}

代码示例来源:origin: reactor/reactor-core

@Test
public void contextSimple3() {
  String key = "message";
  Mono<String> r = Mono.subscriberContext() // <1>
             .map( ctx -> ctx.put(key, "Hello")) // <2>
             .flatMap( ctx -> Mono.subscriberContext()) // <3>
             .map( ctx -> ctx.getOrDefault(key,"Default")); // <4>
  StepVerifier.create(r)
        .expectNext("Default") // <5>
        .verifyComplete();
}

代码示例来源:origin: reactor/reactor-core

@Test
public void withInitialContext() {
  StepVerifier.create(Mono.subscriberContext(),
      StepVerifierOptions.create().withInitialContext(Context.of("foo", "bar")))
        .assertNext(c -> Assertions.assertThat(c.getOrDefault("foo", "baz"))
                      .isEqualTo("bar"))
        .verifyComplete();
}

代码示例来源:origin: reactor/reactor-core

static final OnNextFailureStrategy onNextErrorStrategy(Context context) {
  OnNextFailureStrategy strategy = null;
  BiFunction<? super Throwable, Object, ? extends Throwable> fn = context.getOrDefault(
      OnNextFailureStrategy.KEY_ON_NEXT_ERROR_STRATEGY, null);
  if (fn instanceof OnNextFailureStrategy) {
    strategy = (OnNextFailureStrategy) fn;
  } else if (fn != null) {
    strategy = new OnNextFailureStrategy.LambdaOnNextErrorStrategy(fn);
  }
  if (strategy == null) strategy = Hooks.onNextErrorHook;
  if (strategy == null) strategy = OnNextFailureStrategy.STOP;
  return strategy;
}

代码示例来源:origin: reactor/reactor-core

@Test
public void discardAdapterIsAdditive() {
  List<String> discardOrder = Collections.synchronizedList(new ArrayList<>(2));
  Function<Context, Context> first = Operators.discardLocalAdapter(Number.class, i -> discardOrder.add("FIRST"));
  Function<Context, Context> second = Operators.discardLocalAdapter(Integer.class, i -> discardOrder.add("SECOND"));
  Context ctx = first.apply(second.apply(Context.empty()));
  Consumer<Object> test = ctx.getOrDefault(Hooks.KEY_ON_DISCARD, o -> {});
  assertThat(test).isNotNull();
  test.accept(1);
  assertThat(discardOrder).as("consumers were combined").containsExactly("FIRST", "SECOND");
}

代码示例来源:origin: reactor/reactor-core

@Test
public void of2() throws Exception {
  Context c = Context.of(1, 100, 2, 200);
  assertThat(c).isInstanceOf(Context2.class);
  assertThat(c.isEmpty()).as("isEmpty").isFalse();
  assertThat(c.stream()).hasSize(2);
}

代码示例来源:origin: reactor/reactor-core

@Test
public void putAllOfEmpty() {
  Context m = Context.empty();
  Context put = c.putAll(m);
  assertThat(put).isSameAs(c);
}

代码示例来源:origin: reactor/reactor-core

@Test
public void putAllOfContext3() {
  Context m = Context.of("A", 1, "B", 2, "C", 3);
  Context put = c.putAll(m);
  assertThat(put).isInstanceOf(ContextN.class);
  assertThat(put.stream().map(Map.Entry::getKey))
      .containsExactlyInAnyOrder(1, 2, 3, 4, 5, 6, "A", "B", "C");
}

代码示例来源:origin: reactor/reactor-core

@Test
public void get() {
  assertThat((String) c.get(1)).isEqualTo("A");
  assertThat((String) c.get(2)).isEqualTo("B");
  assertThat((String) c.get(3)).isEqualTo("C");
  assertThat((String) c.get(4)).isEqualTo("D");
  assertThat((String) c.get(5)).isEqualTo("E");
  assertThat((String) c.get(6)).isEqualTo("F");
}

代码示例来源:origin: reactor/reactor-core

@Test
public void putAllOf() {
  Context m = Context.of("A", 1, "B", 2, "C", 3);
  Context put = c.putAll(m);
  assertThat(put).isInstanceOf(Context3.class)
          .hasToString("Context3{A=1, B=2, C=3}");
}

代码示例来源:origin: reactor/reactor-core

@Test
public void putAllOf() {
  Context m = Context.of("A", 1, "B", 2, "C", 3);
  Context put = c.putAll(m);
  assertThat(put).isInstanceOf(ContextN.class);
  assertThat(put.stream().map(Map.Entry::getKey))
      .containsExactlyInAnyOrder(1, 2, 3, 4, "A", "B", "C");
}

相关文章