下面列出了怎么用org.springframework.context.event.EventListener的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
@Async
@EventListener
public synchronized void onEntityMove(EntityMoveEvent e) {
Entity movingEntity = e.getEntity();
// When the entity is in the same Chunk, just return
if (ChunkCoords.of(e.getOldPosition()).equals(ChunkCoords.of(e.getNewPosition()))) {
return;
}
Collection<Entity> inRangeEntities = getInRangeEntities(movingEntity);
if (isObserver(movingEntity)) {
makeTheObserverUntrackOutOfRangeEntities(movingEntity, inRangeEntities);
makeTheObserverTrackInRangeEntities(movingEntity, inRangeEntities);
}
makeInRangeObserversTrackTheEntity(movingEntity, inRangeEntities);
makeOutOfRangeObserversUntrackTheEntity(movingEntity, inRangeEntities);
}
@EventListener(condition = "#event.topic=='test'")
public void testListen(RocketmqEvent event) {
MQPushConsumer consumer = consumerTemplate.getConsumer();
try {
String id = new String(event.getMessageExt().getBody(),"utf-8");
System.out.println("bl"+ id);
} catch (Exception e) {
e.printStackTrace();
if (event.getMessageExt().getReconsumeTimes() <= 1) {// 重复消费1次
try {
consumer.sendMessageBack(event.getMessageExt(), 1, null);
} catch (RemotingException | MQBrokerException | InterruptedException | MQClientException e1) {
e1.printStackTrace();
//消息进行定时重试
}
} else {
System.out.println("消息消费失败,定时重试");
}
}
}
@EventListener
public void auditEventHappened(AuditApplicationEvent auditApplicationEvent) {
AuditEvent auditEvent = auditApplicationEvent.getAuditEvent();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Principal ").append(auditEvent.getPrincipal()).append(" - ").append(auditEvent.getType());
stringBuilder.append("\n Authorities: ").append(auditEvent.getData().get("authorities"));
WebAuthenticationDetails details = (WebAuthenticationDetails) auditEvent.getData().get("details");
loginAttemptService.loginAttempt(auditEvent);
if (details != null) {
stringBuilder.append("\n Remote IP address: ").append(details.getRemoteAddress());
stringBuilder.append("\n Session ID: ").append(details.getSessionId());
}
stringBuilder.append("\n Request URL: ").append(auditEvent.getData().get("requestUrl"));
stringBuilder.append("\n Source: ").append(auditEvent.getData().get("source"));
String message = stringBuilder.toString();
if (auditEvent.getType().equals(AuthenticationAuditListener.AUTHENTICATION_FAILURE)) {
log.warn(message);
} else {
log.info(message);
}
}
@SuppressWarnings("rawtypes")
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
final Environment environment = event.getApplicationContext().getEnvironment();
LOGGER.info("====== Environment and configuration ======");
LOGGER.info("Active profiles: {}", Arrays.toString(environment.getActiveProfiles()));
final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources();
StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource)
.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct()
.forEach(prop -> {
Object resolved = environment.getProperty(prop, Object.class);
if (resolved instanceof String) {
LOGGER.info("{} - {}", prop, environment.getProperty(prop));
} else {
LOGGER.info("{} - {}", prop, "NON-STRING-VALUE");
}
});
LOGGER.debug("===========================================");
}
@EventListener(ApplicationReadyEvent.class)
public void process() throws Exception {
try (Stream<String> stream = Files.lines(Paths.get(moviesFile.getURI()))) {
stream.forEach(s -> {
Movie movie = Parser.parseMovie(s);
log.info("sending " + movie.getMovieId() + " for movie " + movie.toString() + " to " + MOVIES_TOPIC);
movieTemplate.send(MOVIES_TOPIC, movie.getMovieId(), movie);
});
}
catch (IOException e) {
e.printStackTrace();
}
Random ran = new Random();
while (true) {
int movieId = ran.nextInt(920) + 1;
int rating = 5 + ran.nextInt(6);
Rating rat = new Rating((long) movieId, (double) rating);
log.info(rat.toString());
Thread.sleep(1_000);
this.ratingTemplate.send(KafkaBasicsApplication.RATINGS_TOPIC, rat.getMovieId(), rat);
}
}
/**
* Metacat service shutdown.
*
* @param event Event when the context is shutting down
*/
@EventListener
public void stop(final ContextClosedEvent event) {
log.info("Metacat application is stopped per {}. Stopping services.", event);
try {
this.pluginsLoaded.set(false);
this.connectorManager.stop();
this.catalogsLoaded.set(false);
this.threadServiceManager.stop();
this.metacatThriftService.stop();
this.thriftStarted.set(false);
} catch (final Exception e) {
// Just log it since we're shutting down anyway shouldn't matter to propagate it
log.error("Unable to properly shutdown services due to {}", e.getMessage(), e);
}
log.info("Finished stopping services.");
}
@EventListener(ApplicationStartedEvent.class)
public void generateDefaultData() {
Long count = carRepository.count();
if (count == 0L) {
List<String> colors = List.of("Black", "White", "Red", "Blue");
List<Car> carList = new ArrayList<>();
Date newDate = new Date();
for (int i = 0; i < 500; i++) {
carList.add(
Car.builder()
.brand("HKCar")
.colour(colors.get(i % 3))
.date(newDate)
.doorCount(4)
.fuel("Diesel")
.model("SuperCar")
.serial("SR" + i)
.type("TypeC")
.year(2020)
.build()
);
}
carRepository.saveAll(carList);
}
}
/**
* 新区块生成后,clear掉map中number比区块小的所有数据
*/
@Order(3)
@EventListener(AddBlockEvent.class)
public void blockGenerated(AddBlockEvent addBlockEvent) {
Block block = (Block) addBlockEvent.getSource();
int number = block.getBlockHeader().getNumber();
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (String key : blockConcurrentHashMap.keySet()) {
if (blockConcurrentHashMap.get(key).getNumber() <= number) {
blockConcurrentHashMap.remove(key);
}
}
return null;
});
}
@Order(value = 50)
@EventListener
public void onTerminate(AsyncPlayerTerminationEvent e) {
Player player = e.getPlayer();
if (player.getEntity() == null) {
return;
}
EntityData entityData = new EntityData(player.getEntity().getPosition(),
player.getEntity().getWorld().getID(), player.getGameMode(), player.isFlying());
try {
playerManager.getPlayerDataSource().setPlayerData(player, StandardPlayerDataType.ENTITY_DATA,
entityData);
} catch (IOException e1) {
log.error("Failed to save player data for " + player, e1);
}
}
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
log.info("start data initialization...");
this.databaseClient.delete().from("posts")
.then().
and(
this.databaseClient.insert()
.into("posts")
//.nullValue("id", Integer.class)
.value("title", "First post title")
.value("content", "Content of my first post")
.map((r, m) -> r.get("id", Integer.class)).all()
.log()
)
.thenMany(
this.databaseClient.select()
.from("posts")
.orderBy(Sort.by(desc("id")))
.as(Post.class)
.fetch()
.all()
.log()
)
.subscribe(null, null, () -> log.info("initialization is done..."));
}
@EventListener
public void onApplicationReadyEvent(ApplicationReadyEvent event) {
Flux
.interval(Duration.ofMillis(1000))
.flatMap(tick -> repository.findAll())
.map(image -> {
Comment comment = new Comment();
comment.setImageId(image.getId());
comment.setComment(
"Comment #" + counter.getAndIncrement());
return Mono.just(comment);
})
.flatMap(newComment ->
Mono.defer(() ->
controller.addComment(newComment)))
.subscribe();
}
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
log.info("start data initialization ...");
this.posts
.deleteAll()
.thenMany(
Flux
.just("Post one", "Post two")
.flatMap(
title -> this.posts.save(Post.builder().title(title).content("content of " + title).build())
)
)
.log()
.subscribe(
null,
null,
() -> log.info("done initialization...")
);
}
@EventListener(ApplicationReadyEvent.class)
public void onApplicationReady() {
log.info("application ready");
sysPropertyDs.createSysPropertyTable();
int dbSqlVer = this.upgradeSql();
if (dbSqlVer != HyenaConstants.SQL_VERSION) {
sysPropertyDs.setSqlVersion(HyenaConstants.SQL_VERSION);
}
}
@EventListener
public void revoked(OnRevokedEvent event) {
if (leader) {
leader = false;
log.info("Transitioned to follower");
}
}
@EventListener
public void onJobStatusChange(JobStatusChangeEvent event) {
Job job = event.getJob();
if (!job.isDone()) {
return;
}
StatsType t = defaultTypes.get(StatsType.JOB_STATUS);
StatsItem item = t.createEmptyItem();
item.getCounter().put(job.getStatus().name(), 1.0F);
int day = DateHelper.toIntDay(job.getCreatedAt());
add(job.getFlowId(), day, item.getType(), item.getCounter());
}
@Override
@Transactional
@EventListener
public void handle(BookPlacedOnHold event) {
try {
createNewHold(event);
} catch (DuplicateKeyException ex) {
//idempotent operation
}
}
@EventListener
public void on(final MessageReceiverNotification notification) {
if (notification.getStatus() == MessageReceiverStatus.RUNNING) {
notification.getChannelDurationBehind().ifPresent(channelDurationBehind -> {
if (channelDurationBehind.getDurationBehind().toMillis() <= TEN_SECONDS) {
healthyChannels.add(notification.getChannelName());
}
});
}
}
@Order(Ordered.LOWEST_PRECEDENCE)
@EventListener
public void successfullyAnnounce(final SuccessfullyAnnounceEvent event) {
logger.debug("Send SuccessfullyAnnouncePayload to clients.");
this.messagingTemplate.convertAndSend("/announce", new SuccessfullyAnnouncePayload(event));
}
@EventListener
public void onPostSaved(Post savedPost) {
LOG.debug("=================received post data============== @\r\n"+ savedPost);
ESPost doc=new ESPost();
doc.setId("1");
doc.setTitle(savedPost.getTitle());
doc.setContent(savedPost.getContent());
repository.save(doc);
}
@Override
@EventListener
public void onJobCreated(JobCreatedEvent event) {
Job job = event.getJob();
socketPushManager.push(topicForJobs, PushEvent.NEW_CREATED, job);
log.debug("Job created event {} been pushed", job.getId());
}
/**
* 服务实例注册事件
* @param event
*/
@EventListener
public void listen(EurekaInstanceRegisteredEvent event) {
/**
* 获取当前已注册的所有服务器实例
*/
int total = EurekaServerContextHolder.getInstance().getServerContext().getRegistry().getSortedApplications().size();
// event.getInstanceInfo().getActionType()
log.info("服务实例[{}]注册成功,当前服务器已注册服务实例数量[{}]", event.getInstanceInfo().getAppName(), total);
}
@EventListener(LightminClientApplicationChangedEvent.class)
public void addJournal(final LightminClientApplicationChangedEvent event) {
final Journal journal = new Journal();
final LightminClientApplication lightminClientApplication = (LightminClientApplication) event.getSource();
journal.setApplicationName(lightminClientApplication.getName());
journal.setHost(lightminClientApplication.getServiceUrl());
journal.setTimestamp(new Date(event.getEventDateInMillis()));
journal.setOldStatus(event.getOldStatus());
journal.setNewStatus(event.getNewStatus());
log.info("Journal change event: {}", journal);
this.journalRepository.add(journal);
}
@EventListener
public void onTestDetailsCreatedEvent(TestDetailsCreatedEvent testDetailsCreatedEvent) {
final ExecutionMetadata metadata = metadataRepository.findById(testDetailsCreatedEvent.getExecutionId());
if (creationLevel.ordinal() >= HtmlGenerationLevel.TEST_DETAILS.ordinal()) {
writeTestDetails(testDetailsCreatedEvent.getTestDetails(), metadata);
}
}
@EventListener
public void onEntityAdd(EntityAddEvent e) {
Entity entity = e.getEntity();
entity.getWorld().getChunkAt(entity.getPosition()).addCallback(chunk -> {
Preconditions.checkNotNull(chunk);
chunk.getEntities().add(entity);
}, Throwable::printStackTrace);
}
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
log.info("start data initialization ...");
this.initPosts();
log.info("done data initialization ...");
//conn.hashCommands().hGetAll(key)
}
/**
* 新增server节点,重新分配任务
* 将现有的任务数 除以节点数量,除得尽就不分配,不然就按照商值进行分配
*/
@EventListener
public void serverNodeAdd(ServerNodeAddEvent event) throws Exception {
final List<String> serverList = zkClient.getTaskGenerator().getSchedulerServer().loadScheduleServerNames();
//黑名单
for (String ip : zkClient.getSchedulerProperties().getIpBlackList()) {
int index = serverList.indexOf(ip);
if (index > -1) {
serverList.remove(index);
}
}
if (!this.zkClient.getTaskGenerator().getSchedulerServer().isLeader(ScheduleServer.getInstance().getUuid(), serverList)) {
log.info("当前server:[" + ScheduleServer.getInstance().getUuid() + "]: 不是负责任务分配的Leader,直接返回");
return;
}
final String path = (String) event.getSource();
final String serverId = path.substring(path.lastIndexOf("/") + 1);
final List<String> tasks = zkClient.getClient().getChildren().forPath(zkClient.getTaskPath());
if (tasks.size() <= serverList.size()) {
log.info("任务数小于 server 节点数, 不进行任务重新分配");
return;
}
final BigDecimal len = new BigDecimal(tasks.size()).divide(new BigDecimal(serverList.size()), 0, RoundingMode.DOWN);
for (int i = 0; i < len.longValue(); i++) {
// 分配指定任务给指定server
assignTask2Server(tasks.get(i), serverId);
}
}
@EventListener
public void on(final MessageReceiverNotification messageEndpointNotification) {
if (messageEndpointNotification.getStatus() == MessageReceiverStatus.FAILED) {
health = Health.down()
.withDetail("channelName", messageEndpointNotification.getChannelName())
.withDetail("message", messageEndpointNotification.getMessage())
.build();
}
}
@EventListener(AppContextInitializedEvent.class)
protected void applicationInitialized() {
if ("CUBA.Platform".equals(config.getKeyForSecurityTokenEncryption())) {
log.warn("\nWARNING:\n" +
"=================================================================\n" +
"'cuba.keyForSecurityTokenEncryption' app property is set to\n " +
"default value. Use a unique value in production environments.\n" +
"=================================================================");
}
}
@EventListener
public void handleUserCreatedEvent(UserCreatedEvent event) {
//生成totp
String key = TotpUtil.getRandomSecretBase32(64);
UserEntity userEntity = event.getUserEntity();
String keyUrl = TotpUtil.generateTotpString(userEntity.getUsername(), domain, key);
//创建一个用户没有操作权限的配置
userSettingManager.saveSetting(userEntity.getId(), settingId, key, UserSettingPermission.NONE);
eventPublisher.publishEvent(new TotpTwoFactorCreatedEvent(userEntity, keyUrl));
}
@EventListener(classes = RemoteApplicationEvent.class)
public void acceptLocal(RemoteApplicationEvent event) {
if (this.serviceMatcher.isFromSelf(event)
&& !(event instanceof AckRemoteApplicationEvent)) {
if (log.isDebugEnabled()) {
log.debug("Sending remote event on bus: " + event);
}
this.cloudBusOutboundChannel.send(MessageBuilder.withPayload(event).build());
}
}