001/*
002 *  Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com).
003 *  <p>
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *  <p>
008 *  http://www.apache.org/licenses/LICENSE-2.0
009 *  <p>
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016
017package com.mybatisflex.core.audit;
018
019import java.util.ArrayList;
020import java.util.Collections;
021import java.util.List;
022import java.util.concurrent.locks.ReentrantReadWriteLock;
023
024/**
025 * 抽象消息收集器。
026 *
027 * @author 王帅
028 * @since 2023-09-28
029 */
030public abstract class AbstractMessageCollector implements MessageCollector {
031
032    private final MessageReporter messageSender;
033    private final List<AuditMessage> messages = Collections.synchronizedList(new ArrayList<>());
034    private final ReentrantReadWriteLock rrwLock = new ReentrantReadWriteLock();
035
036    protected AbstractMessageCollector(MessageReporter messageSender) {
037        this.messageSender = messageSender;
038    }
039
040    @Override
041    public void collect(AuditMessage message) {
042        try {
043            rrwLock.readLock().lock();
044            messages.add(message);
045        } finally {
046            rrwLock.readLock().unlock();
047        }
048    }
049
050    protected void doSendMessages() {
051        if (messages.isEmpty()) {
052            return;
053        }
054        List<AuditMessage> sendMessages;
055        try {
056            rrwLock.writeLock().lock();
057            sendMessages = new ArrayList<>(messages);
058            messages.clear();
059        } finally {
060            rrwLock.writeLock().unlock();
061        }
062        messageSender.sendMessages(sendMessages);
063    }
064
065    public void release() {
066        doSendMessages();
067    }
068
069    protected List<AuditMessage> getMessages() {
070        return messages;
071    }
072
073    protected MessageReporter getMessageSender() {
074        return messageSender;
075    }
076
077}