<!-- 分享充电web模块 -->
<!-- 分享充电公共模块 -->
<!-- 分享充电商城模块 -->
<!-- 分享充电小程序模块 -->
<!-- 分享充电系统模块 -->
<!-- 分享充电业务模块 -->
<!-- 项目构件ID -->
<!-- 项目打包方式 -->
<!-- 项目描述 -->
Spring Cloud OpenFeign 的核心原理是利用 Java 的动态代理和注解来简化 HTTP 请求的构建。开发者只需定义接口,并使用注解描述请求的细节
OpenFeign 允许你使用请求拦截器来修改请求,例如添加 header、日志记录等。
/**
* Actor 系统设置
*/
@Data
// 定义一个ActorSystemSettings类
public class ActorSystemSettings {
// Actor系统的吞吐量
private final int actorThroughput;
// 调度器线程池大小
private final int schedulerPoolSize;
// 最大Actor初始化尝试次数
private final int maxActorInitAttempts;
}
/**
* Actor 线程工厂
*/
public class ActorThreadFactory implements ThreadFactory {
// 定义一个 AtomicInteger 类型的静态变量,用于生成线程池的编号
public static final AtomicInteger poolNumber = new AtomicInteger(1);
// 定义一个 ThreadGroup 类型的变量,用于存储线程组
private final ThreadGroup group;
// 定义一个 AtomicInteger 类型的静态变量,用于生成线程的编号
private static final AtomicInteger threadNumber = new AtomicInteger(1);
// 定义一个 String 类型的变量,用于存储线程的名称前缀
private final String namePrefix;
// 根据给定的名称创建一个ActorThreadFactory对象
public static ActorThreadFactory forName(String name) {
// 创建一个新的ActorThreadFactory对象,并传入名称
return new ActorThreadFactory(name);
}
// 定义一个构造方法,用于初始化ActorThreadFactory对象
public ActorThreadFactory(String name) {
// 获取安全管理器
SecurityManager s = System.getSecurityManager();
// 如果安全管理器不为空,则获取安全管理器的线程组,否则获取当前线程的线程组
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
// 设置线程的名称前缀
namePrefix = name + "-" + poolNumber.getAndIncrement() + "-thread-";
}
// 实现ThreadFactory接口的newThread方法,用于创建新的线程
@Override
public Thread newThread(Runnable r) {
// 创建新的线程
Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
// 如果线程是守护线程,则设置为非守护线程
if (t.isDaemon()) {
t.setDaemon(false);
}
// 如果线程的优先级不是普通优先级,则设置为普通优先级
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
// 返回新的线程
return t;
}
}
@Data
public class Dispatcher {
// 分发器ID
private final String dispatcherId;
// 执行器
private final ExecutorService executor;
}
/**
* Actor 接口
*/
public interface Actor {
// 处理Actor消息
boolean process(ActorMsg msg);// throws ActorException;
// 获取Actor引用
ActorRef getActorRef();// throws ActorException;
// 初始化Actor
default void init(ActorCtx ctx) throws ActorException {
}
// 销毁Actor
default void destroy() throws ActorException {
}
// 初始化失败策略
/**
* 初始化失败策略
* @param attempt 尝试次数
* @param t 异常
* @return
*/
default InitFailureStrategy onInitFailure(int attempt, Throwable t) {
return InitFailureStrategy.retryWithDelay(5000L * attempt);//默认重试
}
// 处理失败策略
default ProcessFailureStrategy onProcessFailure(Throwable t) {
if (t instanceof Error) {//如果是Error则停止
return ProcessFailureStrategy.stop();//停止
} else {
return ProcessFailureStrategy.resume();//继续
}
}
}
/**
* ActorCtx是 ActorRef的扩展,它提供了与Actor生命周期管理相关的功能 Actor 上下文 Actor是 一个对象,它可以在其生命周期内接收消息,并执行相应的操作 ActorCtx 提供了与Actor生命周期管理相关的功能,例如停止Actor、获取Actor的父引用等
*/
public interface ActorCtx extends ActorRef {//ActorRef是Actor的引用,它提供了与Actor通信相关的功能
// 获取当前Actor的ActorId
ActorId getSelf();
// 获取当前Actor的父ActorRef
ActorRef getParentRef();
// 向指定Actor发送消息
/**
* 向指定Actor发送消息
* @param target 目标Actor的ActorId
* @param msg 要发送的消息
*/
void tell(ActorId target, ActorMsg msg);
// 停止指定Actor
void stop(ActorId target);//停止指定Actor
// 获取或创建子Actor
/**
* 获取或创建子Actor
* @param actorId 子Actor的ActorId
* @param dispatcher 子Actor的调度器
* @param creator 子Actor的创建器
* @return 子Actor的ActorRef
*/
ActorRef getOrCreateChildActor(ActorId actorId, Supplier<String> dispatcher, Supplier<ActorCreator> creator);
// 向所有子Actor广播消息
void broadcastToChildren(ActorMsg msg);
// 向满足条件的子Actor广播消息
/**
* 向满足条件的子Actor广播消息
* @param msg 要发送的消息
* @param childFilter 子Actor的过滤条件
*/
void broadcastToChildren(ActorMsg msg, Predicate<ActorId> childFilter);
// 过滤满足条件的子Actor
/**
* 过滤满足条件的子Actor
* @param childFilter 子Actor的过滤条件
* @return
*/
List<ActorId> filterChildren(Predicate<ActorId> childFilter);
}
/**
* ActorMailbox是 Actor的邮箱,负责接收消息,并调用Actor的receive方法处理消息
*/
@Slf4j
@Data
public final class ActorMailbox implements ActorCtx {// Actor上下文
// 高优先级
public static final boolean HIGH_PRIORITY = true;
// 普通优先级
public static final boolean NORMAL_PRIORITY = false;
// 空闲
public static final boolean FREE = false;
// 忙碌
public static final boolean BUSY = true;
// 未准备
public static final boolean NOT_READY = false;
// 准备
public static final boolean READY = true;
// ActorSystem对象
private final ActorSystem system;
// ActorSystem设置
private final ActorSystemSettings settings;
// Actor的ID
private final ActorId selfId;
// 父Actor的引用
private final ActorRef parentRef;
// Actor对象
private final Actor actor;
// 调度器
private final Dispatcher dispatcher;
// 高优先级消息队列
private final ConcurrentLinkedQueue<ActorMsg> highPriorityMsgs = new ConcurrentLinkedQueue<>();// 高优先级消息队列
// 普通优先级消息队列
private final ConcurrentLinkedQueue<ActorMsg> normalPriorityMsgs = new ConcurrentLinkedQueue<>();// 普通优先级消息队列
// 是否忙碌
private final AtomicBoolean busy = new AtomicBoolean(FREE);
// 是否准备
private final AtomicBoolean ready = new AtomicBoolean(NOT_READY);
// 是否正在销毁
private final AtomicBoolean destroyInProgress = new AtomicBoolean();
// 停止原因
private volatile ActorStopReason stopReason;
// 初始化Actor
public void initActor() {
/**
* 初始化Actor
* 1. 调用Actor的init方法
* 2. 设置Actor为准备状态
* 3. 处理消息队列
* 4. 如果初始化失败,则根据策略进行重试或者停止
* 5. 如果初始化成功,则设置Actor为准备状态,并处理消息队列
* 6. 如果初始化失败,则根据策略进行重试或者停止
*
* dispatcher.getExecutor() 获取ActorSystem的线程池
* execute(() -> tryInit(1)) 执行tryInit方法,尝试初始化Actor
*/
dispatcher.getExecutor().execute(() -> tryInit(1));// 初始化Actor
}
// 尝试初始化Actor
/**
* 尝试初始化Actor
*
* @param attempt 尝试次数
*/
private void tryInit(int attempt) {
try {
// 记录调试信息,尝试初始化actor,尝试次数为attempt
log.debug("[{}] Trying to init actor, attempt: {}", selfId, attempt);
// 如果销毁正在进行中,则不进行初始化
if (!destroyInProgress.get()) {
// 初始化actor
actor.init(this);
// 如果销毁正在进行中,则不设置ready状态
if (!destroyInProgress.get()) {
// 设置ready状态
ready.set(READY);
// 尝试处理队列
tryProcessQueue(false);
}
}
} catch (Throwable t) {
// 记录初始化actor失败的信息
/**
* 记录初始化actor失败的信息
* 1. 记录调试信息,尝试初始化actor,尝试次数为attempt,失败原因t
* 2. 调用actor的onInitFailure方法,获取初始化失败策略
* 3. 如果策略是停止或者尝试次数超过了最大尝试次数,则停止尝试
*/
log.debug("[{}] Failed to init actor, attempt: {}", selfId, attempt, t);
// 尝试次数加1
int attemptIdx = attempt + 1;
// 调用actor的onInitFailure方法,获取初始化失败策略
InitFailureStrategy strategy = actor.onInitFailure(attempt, t);
// 如果策略是停止或者尝试次数超过了最大尝试次数,则停止尝试
if (strategy.isStop() ||
(settings.getMaxActorInitAttempts() > 0 && attemptIdx > settings.getMaxActorInitAttempts())) {// 如果策略是停止或者尝试次数超过了最大尝试次数,则停止尝试
log.info("[{}] Failed to init actor, attempt {}, going to stop attempts.", selfId, attempt, t);
// 设置停止原因
stopReason = ActorStopReason.INIT_FAILED;// 设置停止原因
// 销毁actor
destroy();
// 如果策略有重试延迟,则等待一段时间后重试
} else if (strategy.getRetryDelay() > 0) {
// 记录日志,提示初始化actor失败,尝试次数为attempt,将在strategy.getRetryDelay()毫秒后重试
log.info("[{}] Failed to init actor, attempt {}, going to retry in attempts in {}ms", selfId, attempt,
strategy.getRetryDelay());
// 记录日志,提示错误信息
log.debug("[{}] Error", selfId, t);
// 使用调度器等待一段时间后执行重试
// strategy.getRetryDelay() 获取重试延迟时间
// TimeUnit.MICROSECONDS 获取时间单位
// getScheduler 获取调度器
// schedule 执行调度任务
// dispatcher 获取ActorSystem的线程池
system.getScheduler().schedule(() -> dispatcher.getExecutor().execute(() -> tryInit(attemptIdx)), strategy.getRetryDelay(),
TimeUnit.MICROSECONDS);
// 否则立即重试
} else {
// 记录日志,提示初始化actor失败,尝试次数为attempt,立即重试
log.info("[{}] Failed to init actor, attempt {}, going to retry immediately", selfId, attempt);
// 记录日志,提示错误信息
log.debug("[{}] Error", selfId, t);
// 使用执行器立即执行重试
dispatcher.getExecutor().execute(() -> tryInit(attemptIdx));
}
}
}
// 销毁Actor
public void destroy() {
/**
* 如果stopReason为空,则将其设置为ActorStopReason.STOPPED
*/
if (stopReason == null) {
stopReason = ActorStopReason.STOPPED;// 如果stopReason为空,则将其设置为ActorStopReason.STOPPED
}
// 设置destroyInProgress为true,表示正在销毁
destroyInProgress.set(true);
// 在dispatcher的执行器中执行以下代码
dispatcher.getExecutor().execute(() -> {
try {
// 将ready设置为NOT_READY NOT_READY = 0
ready.set(NOT_READY);
// 销毁actor
actor.destroy();
// 遍历highPriorityMsgs,调用onActorStopped方法
// msg.onActorStopped 调用ActorMsg的onActorStopped方法
// stopReason 获取停止原因
highPriorityMsgs.forEach(msg -> msg.onActorStopped(stopReason));
// 遍历normalPriorityMsgs,调用onActorStopped方法
// normalPriorityMsgs 获取普通优先级的消息队列
normalPriorityMsgs.forEach(msg -> msg.onActorStopped(stopReason));
} catch (Throwable t) {
// 如果发生异常,则记录警告日志
log.warn("[{}] Failed to destroy actor: {}", selfId, t);
}
});
}
// 入队
/**
* 入队
*
* @param msg 消息
* @param highPriority 是否为高优先级
*/
private void enqueue(ActorMsg msg, boolean highPriority) {
// 如果销毁正在进行中
if (!destroyInProgress.get()) {
// 如果是高优先级消息
if (highPriority) {
// 将消息添加到高优先级消息队列中
highPriorityMsgs.add(msg);
} else {
// 否则将消息添加到普通优先级消息队列中
normalPriorityMsgs.add(msg);
}
// 尝试处理队列
tryProcessQueue(true);
} else {
// 如果是高优先级消息并且消息类型是UPDATED_MSG
/**
* 如果销毁正在进行中,并且是高优先级消息,并且消息类型是UPDATED_MSG,则调用消息的 onActorStopped 方法,并传入停止原因
* msg.getMsgType() 获取消息类型
* MsgType.UPDATED_MSG 获取消息类型为UPDATED_MSG
*/
if (highPriority && msg.getMsgType().equals(MsgType.UPDATED_MSG)) {// 如果是高优先级消息并且消息类型是UPDATED_MSG
// 同步
synchronized (this) {// 同步
// 如果停止原因是INIT_FAILED
// ActorStopReason.INIT_FAILED 初始化失败
if (stopReason == ActorStopReason.INIT_FAILED) {
// 将销毁进行中的标志设置为false
destroyInProgress.set(false);
// 将停止原因设置为null
stopReason = null;
// 初始化Actor
initActor();
} else {
// 否则调用消息的onActorStopped方法,并传入停止原因
msg.onActorStopped(stopReason);
}
}
} else {
/**
* 否则调用消息的onActorStopped方法,并传入停止原因
*/
msg.onActorStopped(stopReason);
}
}
}
// 尝试处理队列
private void tryProcessQueue(boolean newMsg) {
// 判断MessageBox是否准备好
if (ready.get() == READY) {
// 判断是否有新消息或者是否有高优先级消息或者是否有普通优先级消息
// highPriorityMsgs 获取高优先级消息队列
// normalPriorityMsgs 获取普通优先级消息队列
// newMsg 是否有新消息
// highPriorityMsgs.isEmpty() 高优先级消息队列是否为空
// normalPriorityMsgs.isEmpty() 普通优先级消息队列是否为空
// 如果有新消息或者有高优先级消息或者有普通优先级消息
if (newMsg || !highPriorityMsgs.isEmpty() || !normalPriorityMsgs.isEmpty()) {
// 尝试将MessageBox状态设置为BUSY
// busy.compareAndSet 比较并设置
// FREE = 0 BUSY = 1
if (busy.compareAndSet(FREE, BUSY)) {
// 如果成功,则执行processMailbox方法
dispatcher.getExecutor().execute(this::processMailbox);
} else {
// 如果失败,则记录日志
log.trace("[{}] MessageBox is busy, new msg: {}", selfId, newMsg);
}
} else {
// 如果没有新消息,则记录日志
log.trace("[{}] MessageBox is empty, new msg: {}", selfId, newMsg);
}
} else {
// 如果MessageBox没有准备好,则记录日志
log.trace("[{}] MessageBox is not ready, new msg: {}", selfId, newMsg);
}
}
// 处理邮箱
/**
* processMailbox 方法用于处理邮箱中的消息。
*/
private void processMailbox() {
// 定义一个布尔变量,表示是否还有元素
boolean noMoreElements = false;
// 循环处理消息,次数为设置的actorThroughput
// settings.getActorThroughput() 获取设置的actorThroughput
// highPriorityMsgs 获取高优先级消息队列
// normalPriorityMsgs 获取普通优先级消息队列
for (int i = 0; i < settings.getActorThroughput(); i++) {
// 从高优先级消息队列中取出一个消息
ActorMsg msg = highPriorityMsgs.poll();
// 如果高优先级消息队列为空,则从普通优先级消息队列中取出一个消息
if (msg == null) {
msg = normalPriorityMsgs.poll();
}
// 如果取到了消息,则处理该消息
if (msg != null) {
log.debug("[{}] Going to process message: {}", selfId, msg);// 记录日志
actor.process(msg);// 处理消息
} else {
// 如果没有取到消息,则表示没有更多元素,跳出循环
noMoreElements = true;
break;
}
}
// 如果没有更多元素,则将busy状态设置为FREE,并执行tryProcessQueue方法
if (noMoreElements) {// 如果没有更多元素
busy.set(FREE);// 将busy状态设置为FREE
// 如果还有更多元素,则执行processMailbox方法
/**
* tryProcessQueue 方法用于尝试处理邮箱中的消息。
* 如果邮箱中还有消息,则将MessageBox状态设置为BUSY,并执行processMailbox方法。
* 如果邮箱中没有消息,则将MessageBox状态设置为FREE,并记录日志。
* 如果MessageBox没有准备好,则记录日志。
* @param newMsg 是否有新消息
*/
dispatcher.getExecutor().execute(() -> tryProcessQueue(false));// 执行tryProcessQueue方法
} else {
// 如果还有更多元素,则执行processMailbox方法
/**
* processMailbox 方法用于处理邮箱中的消息。
*/
dispatcher.getExecutor().execute(this::processMailbox);
}
}
@Override
public ActorId getSelf() {// 获取当前Actor的ID
// 获取当前Actor的ID
return selfId;// 获取当前Actor的ID
}
/**
* @param target 目标Actor的ActorId
* @param msg 要发送的消息
*/
@Override
public void tell(ActorId target, ActorMsg msg) {// 向指定Actor发送消息
// 向指定Actor发送消息
system.tell(target, msg);
}
@Override
public void stop(ActorId target) {// 停止指定Actor
// 停止指定Actor
system.stop(target);
}
/**
* getOrCreateChildActor 方法用于获取或创建子Actor。
* @param actorId 子Actor的ActorId
* @param dispatcher 子Actor的调度器
* @param creator 子Actor的创建器
* @return
*/
@Override
public ActorRef getOrCreateChildActor(ActorId actorId, Supplier<String> dispatcher, Supplier<ActorCreator> creator) {
// 获取或创建子Actor
ActorRef actorRef = system.getActor(actorId);// 获取子Actor
if (actorRef == null) {// 如果子Actor不存在
/**
* createChildActor 方法用于创建子Actor。
* dispatcher.get() 获取调度器
* creator.get() 获取创建器
* selfId 获取当前Actor的ID
*/
return system.createChildActor(dispatcher.get(), creator.get(), selfId);// 创建子Actor
} else {
return actorRef;// 返回子Actor
}
}
/**
* broadcastToChildren 方法用于向所有子Actor广播消息。
* @param msg 要广播的消息
*/
@Override
public void broadcastToChildren(ActorMsg msg) {
// 向所有子Actor广播消息
system.broadcastToChildren(selfId, msg);// 向所有子Actor广播消息
}
/**
* broadcastToChildren 方法用于向满足条件的子Actor广播消息。
* @param msg 要发送的消息
* @param childFilter 子Actor的过滤条件
*/
@Override
public void broadcastToChildren(ActorMsg msg, Predicate<ActorId> childFilter) {
// 向满足条件的子Actor广播消息
system.broadcastToChildren(selfId, childFilter, msg);
}
/**
* filterChildren 方法用于过滤满足条件的子Actor。
* @param childFilter 子Actor的过滤条件
* @return
*/
@Override
public List<ActorId> filterChildren(Predicate<ActorId> childFilter) {
// 过滤满足条件的子Actor
return system.filterChildren(selfId, childFilter);// 过滤满足条件的子Actor
}
/**
* getActorId 方法用于获取当前Actor的ID。
* @return
*/
@Override
public ActorId getActorId() {// 获取当前Actor的ID
// 获取当前Actor的ID
return selfId;
}
/**
* tell 方法用于向当前Actor发送消息。
* @param actorMsg 要发送的消息
*/
@Override
public void tell(ActorMsg actorMsg) {
// 向当前Actor发送消息,优先级为NORMAL_PRIORITY
enqueue(actorMsg, NORMAL_PRIORITY);// 向当前Actor发送消息,优先级为NORMAL_PRIORITY
}
@Override
public void tellWithHighPriority(ActorMsg actorMsg) {
// 向当前Actor发送消息,优先级为HIGH_PRIORITY
enqueue(actorMsg, HIGH_PRIORITY);
}
}
/**
* ActorRef是 Actor的引用,通过ActorRef可以发送消息给Actor
*/
public interface ActorRef {
// 获取Actor的ID
ActorId getActorId();
// 发送消息给Actor
void tell(ActorMsg actorMsg);
// 以高优先级发送消息给Actor
void tellWithHighPriority(ActorMsg actorMsg);
}
// 定义一个枚举类型ActorStopReason,表示Actor停止的原因
public enum ActorStopReason {
// 初始化失败
INIT_FAILED,
// 手动停止
STOPPED
}
/**
* InitFailureStrategy 类,用于定义初始化失败时的策略
*/
@ToString
public class InitFailureStrategy {
// 是否停止
@Getter
private boolean stop;
// 重试延迟时间
@Getter
private long retryDelay;
// 构造函数,传入是否停止和重试延迟时间
private InitFailureStrategy(boolean stop, long retryDelay) {
this.stop = stop;// 是否停止
this.retryDelay = retryDelay;// 重试延迟时间
}
// 立即重试
public static InitFailureStrategy retryImmediately() {// 立即重试
return new InitFailureStrategy(false, 0);// 立即重试
}
// 延迟重试
public static InitFailureStrategy retryWithDelay(long ms) {// 延迟重试
return new InitFailureStrategy(false, ms);// 延迟重试
}
// 停止
public static InitFailureStrategy stop() {// 停止
return new InitFailureStrategy(true, 0);// 停止
}
}
/**
* ProcessFailureStrategy 类,用于定义处理失败时的策略
*/
@ToString
public class ProcessFailureStrategy {// 定义一个ProcessFailureStrategy类
// 定义一个布尔类型的stop变量
@Getter
private boolean stop;
// 构造函数,传入一个布尔类型的参数stop
private ProcessFailureStrategy(boolean stop) {
this.stop = stop;
}
// 返回一个stop为true的ProcessFailureStrategy对象
public static ProcessFailureStrategy stop() {// 定义一个stop方法,返回一个stop为true的ProcessFailureStrategy对象
return new ProcessFailureStrategy(true);
}
// 返回一个stop为false的ProcessFailureStrategy对象
/**
* resume 方法,返回一个stop为false的ProcessFailureStrategy对象
*
* @return
*/
public static ProcessFailureStrategy resume() {// 定义一个resume方法,返回一个stop为false的ProcessFailureStrategy对象
return new ProcessFailureStrategy(false);
}
}
/**
* ActorNotRegisteredException 类,用于定义Actor未注册时的异常
*/
public class ActorNotRegisteredException extends RuntimeException {
// 定义一个ActorId类型的私有变量target
@Getter
private ActorId target;
/**
* 构造函数,传入ActorId类型的target和String类型的message
* @param target ActorId类型的target
* @param message String类型的message
*/
public ActorNotRegisteredException(ActorId target, String message) {
// 调用父类的构造函数,传入message
super(message);
// 将传入的target赋值给私有变量target
this.target = target;
}
}
public interface ActorMsg {
// 获取消息类型
MsgType getMsgType();
// 默认的Actor停止处理方法
/**
* Actor停止处理方法
* @param reason 停止原因
*/
default void onActorStopped(ActorStopReason reason) {
}
}
/**
* EntityActorId 类,实现ActorId接口
*/
public class EntityActorId implements ActorId {
// 定义一个私有的final字符串变量entityId
@Getter
private final String entityId;
// 构造函数,传入一个字符串参数entityId,并将其赋值给私有变量entityId
public EntityActorId(String entityId) {
this.entityId = entityId;
}
}
// 定义一个枚举类型MsgType,包含两个枚举常量UPDATED_MSG和QUEUE_TO_RULE_ENGINE_MSG
public enum MsgType {
// 更新消息
UPDATED_MSG,
// 队列到规则引擎消息
QUEUE_TO_RULE_ENGINE_MSG,
}
@Data
@AllArgsConstructor
public class ActorTestCtx {
// 定义一个CountDownLatch,用于控制线程的执行顺序
private volatile CountDownLatch latch;
// 定义一个AtomicInteger,用于记录方法的调用次数
private final AtomicInteger invocationCount;
// 定义一个int,用于记录预期的方法调用次数
private final int expectedInvocationCount;
// 定义一个AtomicLong,用于记录实际的方法调用次数
private final AtomicLong actual;
// 清空方法,将CountDownLatch重置为1,将invocationCount和actual重置为0
public void clear() {
latch = new CountDownLatch(1);//重置为1
invocationCount.set(0);//重置为0
actual.set(0L);//重置为0
}
}
加群联系作者vx:xiaoda0423