当前位置: 首页>>代码示例>>Java>>正文


Java Schedulers类代码示例

本文整理汇总了Java中reactor.core.scheduler.Schedulers的典型用法代码示例。如果您正苦于以下问题:Java Schedulers类的具体用法?Java Schedulers怎么用?Java Schedulers使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Schedulers类属于reactor.core.scheduler包,在下文中一共展示了Schedulers类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: readEmployeesByDescAge

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
@Override
public Flux<Employee> readEmployeesByDescAge() {
	Scheduler subWorker = Schedulers.newSingle("sub-thread");
	Scheduler pubWorker = Schedulers.newSingle("pub-thread");
	Supplier<Flux<Employee>> deferredTask = ()->{
		System.out.println("flux:defer task executor: "+ Thread.currentThread().getName());
		System.out.println("flux:defer task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		return Flux.fromIterable(employeeDaoImpl.getEmployees());
	};
	Comparator<Employee> descAge = (e1, e2) -> {
		System.out.println("flux:sort task executor: " + Thread.currentThread().getName());
		System.out.println("flux:sort task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		if(e1.getAge().compareTo(e2.getAge()) == 0){
			return 0;
		} else if(e1.getAge().compareTo(e2.getAge()) > 0){
			return -1;
		} else return 1;
	};
	Flux<Employee> deferred = Flux.defer(deferredTask).sort(descAge).subscribeOn(subWorker).publishOn(pubWorker);
	return deferred;
}
 
开发者ID:PacktPublishing,项目名称:Spring-5.0-Cookbook,代码行数:22,代码来源:EmployeeServiceImpl.java

示例2: blockingToReactive

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
@Test
public void blockingToReactive() {

	Callable<String> takesAWhile = () -> {
		Thread.sleep(2000);
		return "Mike";
	};

	Mono<String> naive = Mono.fromCallable(takesAWhile).publishOn(Schedulers.elastic())
			.doOnSubscribe(it -> System.out.println(Thread.currentThread().getName() + ": Subscribe"))
			.doOnSuccess(it -> System.out.println(Thread.currentThread().getName() + ": Success"));

	System.out.println("Before subscribe");
	naive.subscribeOn(Schedulers.parallel()).block();
	System.out.println("After subscribe");
}
 
开发者ID:mp911de,项目名称:reactive-spring,代码行数:17,代码来源:Step7BlockingAndAsync.java

示例3: main

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
public static void main(String[] args) {
  Mono<Integer> mono = Mono.just(2)
      .log()
      .publishOn(Schedulers.parallel())
      .log()
      .map(i -> i * 2)
      .log()
      .publishOn(Schedulers.parallel())
      .log()
      .map(i -> i - 2)
      .log();

  mono.block();
}
 
开发者ID:akiraly,项目名称:playing-reactor,代码行数:15,代码来源:Mono1.java

示例4: main

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
public static void main(String[] args) {
  Flux<LocalDateTime> flux = Flux.<LocalDateTime>create(e -> {
    Schedulers.newSingle("brc", true)
        .schedulePeriodically(
            () -> {
              LOGGER.info("calculating...");
              e.next(LocalDateTime.now(ZoneOffset.UTC));
            },
            0, 100, TimeUnit.MILLISECONDS);
  }, OverflowStrategy.LATEST).cache(1);

  flux.blockFirst();

  while (true) {
    LOGGER.info("{}", flux.blockFirst(Duration.ofMillis(0)));
    Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
  }
}
 
开发者ID:akiraly,项目名称:playing-reactor,代码行数:19,代码来源:BackgroundRefreshingCache.java

示例5: readEmployeesFlux

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
@Override
public Flux<Employee> readEmployeesFlux(int age) {
	Scheduler subWorker = Schedulers.newSingle("sub-thread");
	Scheduler pubWorker = Schedulers.newSingle("pub-thread");
	Predicate<Employee> validAge = (e) -> {
		System.out.println("flux:filter task executor: " + Thread.currentThread().getName());
		System.out.println("flux:filter task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		return e.getAge() > age;
	};
	Supplier<Flux<Employee>> deferredTask = ()->{
		System.out.println("flux:defer task executor: " + Thread.currentThread().getName());
		System.out.println("flux:defer task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		return Flux.fromIterable(employeeDaoImpl.getEmployees());
	};
	Flux<Employee> deferred = Flux.defer(deferredTask).filter(validAge).subscribeOn(subWorker).publishOn(pubWorker);
	return deferred;
}
 
开发者ID:PacktPublishing,项目名称:Spring-5.0-Cookbook,代码行数:18,代码来源:EmployeeServiceImpl.java

示例6: readEmployeesByAscLastName

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
@Override
public Flux<Employee> readEmployeesByAscLastName() {
	Scheduler subWorker = Schedulers.newSingle("sub-thread");
	Scheduler pubWorker = Schedulers.newSingle("pub-thread");
	Supplier<Flux<Employee>> deferredTask = ()->{
		System.out.println("flux:defer task executor: " + Thread.currentThread().getName());
		System.out.println("flux:defer task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		return Flux.fromIterable(employeeDaoImpl.getEmployees());
	};
	Comparator<Employee> descLName = (e1, e2) -> {
		System.out.println("flux:sort task executor: " + Thread.currentThread().getName());
		System.out.println("flux:sort task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		return e1.getLastName().compareTo(e2.getLastName());
	};
	Flux<Employee> deferred = Flux.defer(deferredTask).sort(descLName).subscribeOn(subWorker).publishOn(pubWorker);
	return deferred;
}
 
开发者ID:PacktPublishing,项目名称:Spring-5.0-Cookbook,代码行数:18,代码来源:EmployeeServiceImpl.java

示例7: repeatExecs

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
@Override
public Flux<String> repeatExecs() {
	Function<Employee, String> names = (emp) ->{
		System.out.println("flatMap thread: " + Thread.currentThread().getName());
		return emp.getFirstName().charAt(0) + emp.getLastName();
	};
	
	Flux<String> parallelEmpFlux = Flux.fromIterable(employeeDaoImpl.getEmployees())
       .repeat(2)
	.parallel(8) 
       .runOn (Schedulers.parallel())
       .sequential()
       .map(names)
       .doOnSubscribe(subscription ->
       {
           subscription.request(2);
           System.out.println(subscription);
       });
       
	return parallelEmpFlux;
}
 
开发者ID:PacktPublishing,项目名称:Spring-5.0-Cookbook,代码行数:22,代码来源:EmployeeParallelStreamServiceImpl.java

示例8: WebSocketSubscriber

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
/**
 * Creates a new subscriber which receives {@link Serializable} data and emits it on a websocket.
 *
 * @param writer The writer for serializing received Serializables
 * @param uri    The URI  of the websocket (eg. '/route').
 * @param port   The port of the websocket (eg. 1337).
 */
public WebSocketSubscriber(
    final Function<T, String> writer,
    final String uri,
    final int port) {
  this.writer = writer;
  HttpServer.create(port)
      .newHandler((in, out) ->
          in.uri().equals(uri)
              ? out.sendWebsocket((inboundWebsocket, outboundWebsocket) ->
              outboundWebsocket
                  .options(NettyPipeline.SendOptions::flushOnEach)
                  .sendString(this.outputPublisher))
              : out.sendNotFound())
      .subscribeOn(Schedulers.single())
      .subscribe();
}
 
开发者ID:delta-leonis,项目名称:zosma,代码行数:24,代码来源:WebSocketSubscriber.java

示例9: decide

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
public Mono<Boolean> decide(Authentication authentication, Object object, Flux<ConfigAttribute> configAttributes) {
	return Mono
		.just(Tuples.of(authentication, object, configAttributes))
		.publishOn(Schedulers.elastic())
		.filter((Tuple3<Authentication, Object, Flux<ConfigAttribute>> t) -> {
			Authentication auth = t.getT1();
			return auth != null && auth.isAuthenticated();
		})
		.then((Function<Tuple3<Authentication, Object, Flux<ConfigAttribute>>, Mono<Boolean>>) t -> {
			List<ConfigAttribute> attrs = new ArrayList<>();
			t.getT3().toIterable().forEach(attrs::add);

			try {
				accessDecisionManager.decide(t.getT1(), t.getT2(), attrs);
				return Mono.just(true);
			} catch(AccessDeniedException fail) {
				return Mono.just(false);
			}
		});
}
 
开发者ID:guilhebl,项目名称:item-shop-reactive-backend,代码行数:21,代码来源:ReactiveAccessDecisionManagerAdapter.java

示例10: decide

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
public Mono<Boolean> decide(Authentication authentication, Object object, Flux<ConfigAttribute> configAttributes) {
	return Mono
		.just(Tuples.of(authentication, object, configAttributes))
		.publishOn(Schedulers.elastic())
		.filter((Tuple3<Authentication, Object, Flux<ConfigAttribute>> t) -> {
			Authentication auth = t.getT1();
			return auth != null && auth.isAuthenticated();
		})
		.flatMap((Function<Tuple3<Authentication, Object, Flux<ConfigAttribute>>, Mono<Boolean>>) t -> {
			List<ConfigAttribute> attrs = new ArrayList<>();
			t.getT3().toIterable().forEach(attrs::add);

			try {
				accessDecisionManager.decide(t.getT1(), t.getT2(), attrs);
				return Mono.just(true);
			} catch(AccessDeniedException fail) {
				return Mono.just(false);
			}
		});
}
 
开发者ID:spring-projects,项目名称:spring-security-reactive,代码行数:21,代码来源:ReactiveAccessDecisionManagerAdapter.java

示例11: start

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
@Override
public void start() {
	if(this.concurrency == null){
		// We are assuming Brian Goetz (http://www.ibm.com/developerworks/java/library/j-jtp0730/index.html) cores * 1 + (1 + wait/service) and that http wait is taking 2x more than service
		this.concurrency = Runtime.getRuntime().availableProcessors() * 3;
	}
	this.processorCancellation = processor.groupBy(PubSubMessage::getTopic)
			.flatMap(group -> group.map(pubSubMessage -> {
				return pubSubMessage.getMessage();
			}).buffer(producerProperties.getExtension().getBatchSize(), Duration.ofMillis(producerProperties.getExtension().getWindowSize())).map(messages -> {
				return new GroupedMessage(group.key(), messages);
			})).parallel(concurrency).runOn(Schedulers.elastic()).doOnNext(groupedMessage -> {
				logger.info("Dispatching messages");
				resourceManager.publishMessages(groupedMessage);
			}).sequential().publishOn(Schedulers.elastic()).subscribe();
	running = true;
}
 
开发者ID:viniciusccarvalho,项目名称:spring-cloud-stream-binder-pubsub,代码行数:18,代码来源:BatchingPubSubMessageHandler.java

示例12: queryAsync

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
/**
 * Query async.
 *
 * @param array the array
 * @param query the query
 * @return the observable
 */
private Flux<JsonElement> queryAsync(JsonArray array, JsonObject query) {
  return Flux.fromIterable(array)
      .publishOn(Schedulers.elastic())
      .filter(json -> filter(json, query.get("where")))
      .compose(
          obs -> {
            Long limit = jsonLever.asLong(query.get("limit"), 0L);
            return limit > 0 ? obs.take(limit.intValue()) : obs;
          })
      .publishOn(Schedulers.elastic())
      .compose(
          obs ->
              StringUtils.equals(jsonLever.getString(query, "select"), "count")
                  ? obs.count().map(count -> new JsonPrimitive(count))
                  : obs.map(json -> select(json, query.get("select"))));
}
 
开发者ID:balajeetm,项目名称:json-mystique,代码行数:24,代码来源:JsonQuery.java

示例13: scanMainSubscriber

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
@Test
public void scanMainSubscriber() {
    CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
    FluxSubscribeOnValue.ScheduledScalar<Integer> test =
    		new FluxSubscribeOnValue.ScheduledScalar<Integer>(actual, 1, Schedulers.single());

    assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
    assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(1);

    assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
    test.future = FluxSubscribeOnValue.ScheduledScalar.FINISHED;
    assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();

    assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
    test.future = OperatorDisposables.DISPOSED;
    assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
}
 
开发者ID:reactor,项目名称:reactor-core,代码行数:18,代码来源:FluxSubscribeOnValueTest.java

示例14: allEnabled

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
@Test
public void allEnabled() {
	Assert.assertFalse(Schedulers.newParallel("") instanceof VirtualTimeScheduler);
	Assert.assertFalse(Schedulers.newElastic("") instanceof VirtualTimeScheduler);
	Assert.assertFalse(Schedulers.newSingle("") instanceof VirtualTimeScheduler);

	VirtualTimeScheduler.getOrSet();

	Assert.assertTrue(Schedulers.newParallel("") instanceof VirtualTimeScheduler);
	Assert.assertTrue(Schedulers.newElastic("") instanceof VirtualTimeScheduler);
	Assert.assertTrue(Schedulers.newSingle("") instanceof VirtualTimeScheduler);

	VirtualTimeScheduler t = VirtualTimeScheduler.get();

	Assert.assertSame(Schedulers.newParallel(""), t);
	Assert.assertSame(Schedulers.newElastic(""), t);
	Assert.assertSame(Schedulers.newSingle(""), t);
}
 
开发者ID:reactor,项目名称:reactor-core,代码行数:19,代码来源:VirtualTimeSchedulerTests.java

示例15: assertNextWithSubscribeOnDirectProcessor

import reactor.core.scheduler.Schedulers; //导入依赖的package包/类
@Test
public void assertNextWithSubscribeOnDirectProcessor() {
	Scheduler scheduler = Schedulers.newElastic("test");
	DirectProcessor<Integer> processor = DirectProcessor.create();
	Mono<Integer> doAction = Mono.fromSupplier(() -> 22)
	                             .doOnNext(processor::onNext)
	                             .subscribeOn(scheduler);

	assertThatExceptionOfType(AssertionError.class)
			.isThrownBy(
					StepVerifier.create(processor)
					            .then(doAction::subscribe)
					            .assertNext(v -> assertThat(v).isEqualTo(23))
					            .thenCancel()
							::verify);
}
 
开发者ID:reactor,项目名称:reactor-core,代码行数:17,代码来源:StepVerifierTests.java


注:本文中的reactor.core.scheduler.Schedulers类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。