From 001d0f5e1c4a3a9ecd2fd88559d29d6b4498c459 Mon Sep 17 00:00:00 2001 From: Suomm <1474983351@qq.com> Date: Thu, 28 Sep 2023 22:09:17 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=8A=BD=E8=B1=A1=E6=B6=88=E6=81=AF?= =?UTF-8?q?=E6=94=B6=E9=9B=86=E5=99=A8=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/audit/AbstractMessageCollector.java | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 mybatis-flex-core/src/main/java/com/mybatisflex/core/audit/AbstractMessageCollector.java diff --git a/mybatis-flex-core/src/main/java/com/mybatisflex/core/audit/AbstractMessageCollector.java b/mybatis-flex-core/src/main/java/com/mybatisflex/core/audit/AbstractMessageCollector.java new file mode 100644 index 00000000..3267c7d7 --- /dev/null +++ b/mybatis-flex-core/src/main/java/com/mybatisflex/core/audit/AbstractMessageCollector.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mybatisflex.core.audit; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +/** + * 抽象消息收集器。 + * + * @author 王帅 + * @since 2023-09-28 + */ +public abstract class AbstractMessageCollector implements MessageCollector { + + private final MessageReporter messageSender; + private final List messages = Collections.synchronizedList(new ArrayList<>()); + private final ReentrantReadWriteLock rrwLock = new ReentrantReadWriteLock(); + + protected AbstractMessageCollector(MessageReporter messageSender) { + this.messageSender = messageSender; + } + + @Override + public void collect(AuditMessage message) { + try { + rrwLock.readLock().lock(); + messages.add(message); + } finally { + rrwLock.readLock().unlock(); + } + } + + protected void doSendMessages() { + if (messages.isEmpty()) { + return; + } + List sendMessages; + try { + rrwLock.writeLock().lock(); + sendMessages = new ArrayList<>(messages); + messages.clear(); + } finally { + rrwLock.writeLock().unlock(); + } + messageSender.sendMessages(sendMessages); + } + + public void release() { + doSendMessages(); + } + + protected List getMessages() { + return messages; + } + + protected MessageReporter getMessageSender() { + return messageSender; + } + +}