自定义责任链Filter实现
核心接口
Filter
package com.xxx.arch.mw.nbp.common.extension;import com.xxx.commons.data.domain.Result;/*** @date 2023/08/25*/
public interface Filter {Result invoke(final Invoker invoker, final Invocation invocation);
}
Invoker
package com.xxx.arch.mw.nbp.common.extension;import com.xxx.commons.data.domain.Result;/*** @date 2023/08/25*/
public interface Invoker {Result invoke(Invocation invocation);
}
Invocation
package com.xxx.arch.mw.nbp.common.extension;import com.xxx.arch.mw.nbp.share.dto.PropertyDTO;/*** @date 2023/08/25*/
public interface Invocation<T> {T getDetail();PropertyDTO getProperty();boolean isAsync();}
关键类
FilterChain
package com.xxx.arch.mw.nbp.common.extension;import com.xxx.arch.mw.nbp.common.annotation.DispatchFilter;import java.util.ArrayList;
import java.util.Collections;
import java.util.List;/*** @date 2023/08/28*/
public class FilterChain {private final List<Filter> filters = new ArrayList<>();public FilterChain() {}public void addFilter(Filter filter) {if (filter == null || filter.getClass().getAnnotation(DispatchFilter.class) == null) {return;}if (this.filters.stream().noneMatch(existFilter -> existFilter.getClass().equals(filter.getClass()))) {this.filters.add(filter);}}public void removeFilter(String filterName) {this.filters.removeIf(filter -> filter.getClass().getAnnotation(DispatchFilter.class).value().equals(filterName));}public void removeFilter(Filter filter) {this.filters.removeIf(aFilter -> aFilter.getClass().equals(filter.getClass()));}public Invoker buildInvokerChain(final Invoker invoker) {Invoker last = invoker;if (!filters.isEmpty()) {this.sort();for (int i = filters.size() - 1; i >= 0; i--) {final Filter filter = filters.get(i);final Invoker next = last;last = invocation -> filter.invoke(next, invocation);}}return last;}public void sort() {Collections.sort(this.filters, FilterComparator.COMPARATOR);}public List<Filter> getFilters() {return filters;}
}
FilterComparator
package com.xxx.arch.mw.nbp.common.extension;import com.xxx.arch.mw.nbp.common.annotation.DispatchFilter;import java.util.Comparator;/*** @date 2023/08/28*/
public class FilterComparator implements Comparator<Object> {public static final Comparator<Object> COMPARATOR = new FilterComparator();@Overridepublic int compare(Object o1, Object o2) {if (o1 == null && o2 == null) {return 0;}if (o1 == null) {return -1;}if (o2 == null) {return 1;}if (o1.equals(o2)) {return 0;}DispatchFilter a1 = o1.getClass().getAnnotation(DispatchFilter.class);DispatchFilter a2 = o2.getClass().getAnnotation(DispatchFilter.class);int n1 = a1 == null ? 0 : a1.order();int n2 = a2 == null ? 0 : a2.order();// never return 0 even if n1 equals n2, otherwise, o1 and o2 will override each other in collection like HashSetreturn n1 > n2 ? 1 : -1;}
}
SingleInvocation
package com.xxx.arch.mw.nbp.common.extension;import com.xxx.arch.mw.nbp.share.dto.PropertyDTO;
import com.xxx.arch.mw.nbp.share.dto.SingleDetailDTO;/*** @date 2023/08/28*/
public class SingleInvocation implements Invocation<SingleDetailDTO> {private final SingleDetailDTO singleDetailDTO;private final PropertyDTO propertyDTO;private final boolean async;public SingleInvocation(SingleDetailDTO singleDetailDTO, PropertyDTO propertyDTO) {this.singleDetailDTO = singleDetailDTO;this.propertyDTO = propertyDTO;this.async = false;}public SingleInvocation(SingleDetailDTO singleDetailDTO, PropertyDTO propertyDTO, boolean async) {this.singleDetailDTO = singleDetailDTO;this.propertyDTO = propertyDTO;this.async = async;}@Overridepublic SingleDetailDTO getDetail() {return singleDetailDTO;}@Overridepublic PropertyDTO getProperty() {return propertyDTO;}@Overridepublic boolean isAsync() {return this.async;}
}
MultiInvocation
package com.xxx.arch.mw.nbp.common.extension;import com.xxx.arch.mw.nbp.share.dto.PropertyDTO;
import com.xxx.arch.mw.nbp.share.dto.SingleDetailDTO;import java.util.List;/*** @date 2023/08/28*/
public class MultiInvocation implements Invocation<List<SingleDetailDTO>> {private final List<SingleDetailDTO> singleDetailDTOS;private final PropertyDTO propertyDTO;private final boolean async;public MultiInvocation(List<SingleDetailDTO> singleDetailDTOS, PropertyDTO propertyDTO) {this.singleDetailDTOS = singleDetailDTOS;this.propertyDTO = propertyDTO;this.async = false;}public MultiInvocation(List<SingleDetailDTO> singleDetailDTOS, PropertyDTO propertyDTO, boolean async) {this.singleDetailDTOS = singleDetailDTOS;this.propertyDTO = propertyDTO;this.async = async;}@Overridepublic List<SingleDetailDTO> getDetail() {return singleDetailDTOS;}@Overridepublic PropertyDTO getProperty() {return propertyDTO;}@Overridepublic boolean isAsync() {return this.async;}
}
自定义Filter
选取几个经典实现
ValidationFilter
package com.xxx.arch.mw.nbp.client.extension;import com.xxx.arch.mw.nbp.common.annotation.DispatchFilter;
import com.xxx.arch.mw.nbp.common.constant.FilterConstants;
import com.xxx.arch.mw.nbp.common.domain.NbpCode;
import com.xxx.arch.mw.nbp.common.exception.NbpException;
import com.xxx.arch.mw.nbp.common.extension.*;
import com.xxx.arch.mw.nbp.share.dto.SingleDetailDTO;
import com.xxx.commons.data.domain.Result;import java.util.List;/*** @date 2023/08/28*/
@DispatchFilter(group = {FilterConstants.PUBLISHER, FilterConstants.EXECUTOR}, value = "validation", order = 20)
public class ValidationFilter implements Filter {@Overridepublic Result invoke(final Invoker invoker, final Invocation invocation) {if (invoker == null) {throw new NbpException(NbpCode.ILLEGAL_PARAM.getCode(), "invoker can't be null");}if (invocation == null) {throw new NbpException(NbpCode.ILLEGAL_PARAM.getCode(), "invocation can't be null");}if (invocation.getDetail() == null) {throw new NbpException(NbpCode.ILLEGAL_PARAM.getCode(), "detail can't be null");}if (invocation.getProperty() == null) {throw new NbpException(NbpCode.ILLEGAL_PARAM.getCode(), "property can't be null");}if (invocation instanceof SingleInvocation) {this.validate(((SingleInvocation) invocation).getDetail());} else if (invocation instanceof MultiInvocation) {List<SingleDetailDTO> singleDetailDTOList = ((MultiInvocation) invocation).getDetail();if (singleDetailDTOList.isEmpty()) {throw new NbpException(NbpCode.ILLEGAL_PARAM.getCode(), "singleDetailList can't be null or empty");}for (SingleDetailDTO singleDetail : singleDetailDTOList) {this.validate(singleDetail);}}return invoker.invoke(invocation);}private void validate(SingleDetailDTO singleDetail) {if (singleDetail == null) {throw new NbpException(NbpCode.ILLEGAL_PARAM.getCode(), "singleDetail can't be null");}if (singleDetail.getTemplateCode() == null) {throw new NbpException(NbpCode.ILLEGAL_PARAM.getCode(), "templateCode can't be null");}if (singleDetail.getUserContext() == null || singleDetail.getUserContext().size() == 0) {throw new NbpException(NbpCode.ILLEGAL_PARAM.getCode(), "userContext can't be null or empty");}}
}
PublishMetricFilter
package com.xxx.arch.mw.nbp.client.extension;import com.xxx.arch.mw.nbp.client.util.EnvUtils;
import com.xxx.arch.mw.nbp.client.util.VersionUtils;
import com.xxx.arch.mw.nbp.common.annotation.DispatchFilter;
import com.xxx.arch.mw.nbp.common.constant.FilterConstants;
import com.xxx.arch.mw.nbp.common.constant.InstanceKey;
import com.xxx.arch.mw.nbp.common.constant.TraceKey;
import com.xxx.arch.mw.nbp.common.domain.NbpCode;
import com.xxx.arch.mw.nbp.common.exception.NbpException;
import com.xxx.arch.mw.nbp.common.extension.*;
import com.xxx.arch.mw.nbp.common.util.TraceUtil;
import com.xxx.arch.mw.nbp.share.dto.MultiResult;
import com.xxx.arch.mw.nbp.share.dto.SingleDetailDTO;
import com.xxx.commons.data.domain.Result;
import com.xxx.commons.data.exception.ServiceException;
import org.apache.commons.lang3.time.StopWatch;import java.util.List;
import java.util.Map;import static com.xxx.arch.mw.nbp.client.logger.LoggerInit.LOGGER_PUBLISH;/*** @date 2023/08/28*/
@DispatchFilter(group = {FilterConstants.PUBLISHER}, value = "publishMetric", order = 200)
public class PublishMetricFilter implements Filter {@Overridepublic Result invoke(final Invoker invoker, final Invocation invocation) {if (Boolean.TRUE.equals(invocation.getProperty().getPublisher().getMetricDisabled())) {return invoker.invoke(invocation);}Result result;StopWatch stopWatch = new StopWatch();try {stopWatch.start();result = invoker.invoke(invocation);stopWatch.stop();if (result.isSuccess()) {MultiResult<SingleDetailDTO> resultData = (MultiResult<SingleDetailDTO>) result.getData();for (SingleDetailDTO singleDetail : resultData.getSuccessList()) {this.log(singleDetail, true, stopWatch, null);}for (SingleDetailDTO singleDetail : resultData.getFailureList()) {this.log(singleDetail, false, stopWatch, null);}} else {// 仅PublishExceptionFilter被禁用才会走该分支if (invocation instanceof SingleInvocation) {this.log(((SingleInvocation) invocation).getDetail(), false, stopWatch,new NbpException(result.getCode(), result.getMessage(), result.getCause()));} else if (invocation instanceof MultiInvocation) {List<SingleDetailDTO> singleDetailDTOList = ((MultiInvocation) invocation).getDetail();for (SingleDetailDTO singleDetail : singleDetailDTOList) {this.log(singleDetail, false, stopWatch,new NbpException(result.getCode(), result.getMessage(), result.getCause()));}}}} catch (Throwable e) {if (stopWatch.isStarted()) {stopWatch.stop();}if (invocation instanceof SingleInvocation) {this.log(((SingleInvocation) invocation).getDetail(), false, stopWatch, e);} else if (invocation instanceof MultiInvocation) {List<SingleDetailDTO> singleDetailDTOList = ((MultiInvocation) invocation).getDetail();for (SingleDetailDTO singleDetail : singleDetailDTOList) {this.log(singleDetail, false, stopWatch, e);}}throw e;}return result;}private void log(SingleDetailDTO singleDetail, boolean success, StopWatch stopWatch,Throwable throwable) {Map<String, Object> systemContext = singleDetail.getSystemContext();LOGGER_PUBLISH.info("NBP-CLIENT METRIC PUBLISH","success={},elapsed={},env={},shadow={},traceId={},rpcId={},version={},"+ "code={},id={},bizKey={},triggerTime={},strategyId={},ruleId={},msgId={},"+ "publishedTime={},publishedIp={},receivedTime={},receivedIp={},"+ "errorCode={}",success, stopWatch.getTime(), EnvUtils.getCurrentEnv().name(),TraceUtil.isShadow(), TraceUtil.getTraceId(), TraceUtil.getRpcId(),VersionUtils.VERSION, singleDetail.getTemplateCode(), singleDetail.getInstanceId(),singleDetail.getBizKey(), singleDetail.getTriggerTime(),systemContext.get(InstanceKey.STRATEGY_ID),systemContext.get(InstanceKey.RULE_ID),singleDetail.getUserContext().get(InstanceKey.DISASTER_MSG_ID),systemContext.get(TraceKey.PUBLISHED_TIME),systemContext.get(TraceKey.PUBLISHED_IP),systemContext.get(TraceKey.RECEIVED_TIME),systemContext.get(TraceKey.RECEIVED_IP),throwable == null ? null : throwable instanceof ServiceException ?((ServiceException) throwable).getCode() : NbpCode.UNKNOWN.getCode(),throwable == null ? null : throwable);}}
PublishTraceFilter
package com.xxx.arch.mw.nbp.client.extension;import com.xxx.arch.mw.nbp.common.annotation.DispatchFilter;
import com.xxx.arch.mw.nbp.common.constant.CommonConstants;
import com.xxx.arch.mw.nbp.common.constant.FilterConstants;
import com.xxx.arch.mw.nbp.common.extension.Filter;
import com.xxx.arch.mw.nbp.common.extension.Invocation;
import com.xxx.arch.mw.nbp.common.extension.Invoker;
import com.xxx.arch.mw.nbp.common.util.TraceUtil;
import com.xxx.arch.mw.nbp.share.dto.PropertyDTO;
import com.xxx.arch.mw.nbp.share.facade.DispatchPublishService;
import com.xxx.commons.data.domain.Result;
import com.xxx.arch.mw.util.RequestCtxUtil;import static com.xxx.arch.mw.nbp.common.util.TraceUtil.*;
import static com.xxx.arch.mw.nbp.common.util.TraceUtil.NBP_RPC_PUB_NAME;/*** @date 2023/08/28*/
@DispatchFilter(group = {FilterConstants.PUBLISHER}, value = "publishTrace", order = 100)
public class PublishTraceFilter implements Filter {@Overridepublic Result invoke(final Invoker invoker, final Invocation invocation) {final PropertyDTO property = invocation.getProperty();if (Boolean.TRUE.equals(property.getPublisher().getEagleEyeDisabled())) {return invoker.invoke(invocation);}Result result;try {TraceUtil.startRpc(String.join(CommonConstants.COLON, DispatchPublishService.class.getCanonicalName(),invocation.getProperty().getTemplateCode()), NBP_PUB_SEND_METHOD_NAME, NBP_RPC_PUB_TYPE);TraceUtil.rpcClientSend();result = invoker.invoke(invocation);final String remoteIp = RequestCtxUtil.getProviderIp();if (remoteIp != null) {TraceUtil.remoteIp(remoteIp);}if (result.isSuccess()) {TraceUtil.attribute(RPC_NAME_KEY, NBP_RPC_PUB_NAME);TraceUtil.rpcClientRecv(RPC_RESULT_SUCCESS, "success");} else {TraceUtil.attribute(RPC_NAME_KEY, NBP_RPC_PUB_NAME);TraceUtil.rpcClientRecv(RPC_RESULT_FAILED, result.getMessage());}} catch (Throwable e) {TraceUtil.attribute(RPC_NAME_KEY, NBP_RPC_PUB_NAME);TraceUtil.rpcClientRecv(RPC_RESULT_FAILED, e.getMessage());throw e;}return result;}
}
PublishExceptionFilter
package com.xxx.arch.mw.nbp.client.extension;import com.xxx.arch.mw.nbp.common.annotation.DispatchFilter;
import com.xxx.arch.mw.nbp.common.constant.FilterConstants;
import com.xxx.arch.mw.nbp.common.domain.NbpCode;
import com.xxx.arch.mw.nbp.common.exception.DegradeException;
import com.xxx.arch.mw.nbp.common.exception.FlowException;
import com.xxx.arch.mw.nbp.common.exception.NbpException;
import com.xxx.arch.mw.nbp.common.exception.RpcException;
import com.xxx.arch.mw.nbp.common.extension.Filter;
import com.xxx.arch.mw.nbp.common.extension.Invocation;
import com.xxx.arch.mw.nbp.common.extension.Invoker;
import com.xxx.commons.data.domain.Result;
import com.xxx.arch.mw.exception.RpcException;/*** @date 2023/08/28*/
@DispatchFilter(group = {FilterConstants.PUBLISHER}, value = "publishException", order = 300)
public class PublishExceptionFilter implements Filter {@Overridepublic Result invoke(final Invoker invoker, final Invocation invocation) {try {Result result = invoker.invoke(invocation);if (!result.isSuccess()) {if (NbpCode.FLOW_CONTROL_DENIED.getCode().equals(result.getCode())) {throw new FlowException(NbpCode.FLOW_CONTROL_DENIED.getCode(), result.getMessage(), result.getCause());} else if (NbpCode.BLACKLIST_DENIED.getCode().equals(result.getCode())) {throw new FlowException(NbpCode.BLACKLIST_DENIED.getCode(), result.getMessage(), result.getCause());} else if (NbpCode.DEGRADED_DENIED.getCode().equals(result.getCode())) {throw new DegradeException(NbpCode.DEGRADED_DENIED.getCode(), result.getMessage(), result.getCause());} else {throw new NbpException(result.getCode(), result.getMessage(), result.getCause());}}return result;} catch (NbpException e) {throw e;} catch (RpcException e) {throw new RpcException(NbpCode.RPC_ERROR.getCode(), e.getMessage(), e.getCause());} catch (Throwable e) {throw new NbpException(NbpCode.UNKNOWN.getCode(), e.getMessage(), e.getCause());}}}
PublishCompressFilter
package com.xxx.arch.mw.nbp.client.extension;import com.xxx.arch.mw.nbp.common.annotation.DispatchFilter;
import com.xxx.arch.mw.nbp.common.constant.CommonConstants;
import com.xxx.arch.mw.nbp.common.constant.FilterConstants;
import com.xxx.arch.mw.nbp.common.converter.ConverterUtil;
import com.xxx.arch.mw.nbp.common.csp.Compressor;
import com.xxx.arch.mw.nbp.common.csp.CompressorEnum;
import com.xxx.arch.mw.nbp.common.csp.CompressorFactory;
import com.xxx.arch.mw.nbp.common.extension.*;
import com.xxx.arch.mw.nbp.share.dto.PropertyDTO;
import com.xxx.arch.mw.nbp.share.dto.SingleDetailDTO;
import com.xxx.commons.data.domain.Result;import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import static com.xxx.arch.mw.nbp.common.constant.InstanceKey.COMPRESSED_ALGORITHM_KEY;
import static com.xxx.arch.mw.nbp.common.constant.InstanceKey.COMPRESSED_CONTEXT_KEY;/*** @date 2023/08/28*/
@DispatchFilter(group = {FilterConstants.PUBLISHER}, value = "publishCompress", order = 700)
public class PublishCompressFilter implements Filter {@Overridepublic Result invoke(final Invoker invoker, final Invocation invocation) {final PropertyDTO propertyDTO = invocation.getProperty();final boolean compressEnabled = propertyDTO.getPublisher().getCompressDisabled() != null ?!propertyDTO.getPublisher().getCompressDisabled() : CommonConstants.USER_CONTEXT_COMPRESS_ENABLED;if (compressEnabled) {final int userContextCompressSizeThreshold = propertyDTO.getPublisher().getCompressSizeThreshold() != null ?propertyDTO.getPublisher().getCompressSizeThreshold() : CommonConstants.USER_CONTEXT_COMPRESS_SIZE_THRESHOLD;final CompressorEnum compressorEnum = CompressorEnum.toEnumFromName(propertyDTO.getPublisher().getCompressAlgorithm());final Compressor compressor = compressorEnum != null ?CompressorFactory.getCompressor(compressorEnum) : CompressorFactory.getDefaultCompressor();if (invocation instanceof SingleInvocation) {this.doProcess(((SingleInvocation) invocation).getDetail(), propertyDTO,userContextCompressSizeThreshold, compressorEnum, compressor);} else if (invocation instanceof MultiInvocation) {List<SingleDetailDTO> singleDetailDTOList = ((MultiInvocation) invocation).getDetail();for (SingleDetailDTO singleDetail : singleDetailDTOList) {this.doProcess(singleDetail, propertyDTO,userContextCompressSizeThreshold, compressorEnum, compressor);}}}return invoker.invoke(invocation);}private void doProcess(SingleDetailDTO singleDetail,PropertyDTO propertyDTO,int userContextCompressSizeThreshold,CompressorEnum compressorEnum,Compressor compressor) {byte[] body = ConverterUtil.toBody(singleDetail.getUserContext());if (body.length > userContextCompressSizeThreshold) {final Map<String, String> remainUnchangedFields = new HashMap<>();propertyDTO.getPublisher().getRemainUnchangedFields().forEach(filed -> {if (singleDetail.getUserContext().containsKey(filed)) {remainUnchangedFields.put(filed, singleDetail.getUserContext().remove(filed));}});if (remainUnchangedFields.size() > 0) {body = ConverterUtil.toBody(singleDetail.getUserContext(), Map.class);}final byte[] compressedBody = compressor.compress(body);final String compressedContext = Base64.getEncoder().encodeToString(compressedBody);if (body.length - compressedContext.length() > CommonConstants.USER_CONTEXT_COMPRESS_REVENUE_THRESHOLD) {singleDetail.getUserContext().clear();singleDetail.getUserContext().put(COMPRESSED_CONTEXT_KEY, compressedContext);if (compressorEnum != null && compressorEnum != Compressor.DEFAULT_COMPRESSOR_ALGORITHM) {singleDetail.getUserContext().put(COMPRESSED_ALGORITHM_KEY, compressorEnum.getName());}}singleDetail.getUserContext().putAll(remainUnchangedFields);}}
}
自定义Invoker
PublishInvoker
package com.xxx.arch.mw.nbp.client.invoker;import com.xxx.arch.mw.nbp.client.configuration.DispatchProperty;
import com.xxx.arch.mw.nbp.common.extension.Invocation;
import com.xxx.arch.mw.nbp.common.extension.Invoker;
import com.xxx.arch.mw.nbp.common.extension.MultiInvocation;
import com.xxx.arch.mw.nbp.common.extension.SingleInvocation;
import com.xxx.arch.mw.nbp.share.dto.SingleDetailDTO;
import com.xxx.arch.mw.nbp.share.facade.DispatchPublishService;
import com.xxx.commons.data.domain.Result;import java.util.ArrayList;
import java.util.List;/*** @date 2023/08/30*/
public class PublishInvoker implements Invoker {private DispatchPublishService publishService;private DispatchProperty dispatchProperty;public PublishInvoker(DispatchPublishService publishService, DispatchProperty dispatchProperty) {this.publishService = publishService;this.dispatchProperty = dispatchProperty;}@Overridepublic Result invoke(Invocation invocation) {List<SingleDetailDTO> singleDetailDTOS = new ArrayList<>();if (invocation instanceof SingleInvocation) {singleDetailDTOS.add(((SingleInvocation) invocation).getDetail());} else if (invocation instanceof MultiInvocation) {singleDetailDTOS = ((MultiInvocation) invocation).getDetail();}return this.publishService.publish(singleDetailDTOS);}public DispatchProperty getDispatchProperty() {return dispatchProperty;}}
Invoker构建与使用
public static final List<Filter> PUBLISH_FILTERS = new ArrayList<Filter>() {{add(new ValidationFilter());add(new PublishMetricFilter());add(new PublishExceptionFilter());add(new PublishTraceFilter());add(new PublishCompressFilter());}
};FilterChain publishChain = new FilterChain();
for (Filter filter : ClientFilterConstants.PUBLISH_FILTERS) {publishChain.addFilter(filter);
}Invoker invoker = publishChain.buildInvokerChain(new PublishInvoker(publishService, this.property));Invocation invocation = singleDetailDTOList.size() == 1 ?new SingleInvocation(singleDetailDTOList.get(0), propertyDTO) :new MultiInvocation(singleDetailDTOList, propertyDTO);Result<MultiResult<SingleDetailDTO>> result = invoker.invoke(invocation);
相关文章:
自定义责任链Filter实现
核心接口 Filter package com.xxx.arch.mw.nbp.common.extension;import com.xxx.commons.data.domain.Result;/*** date 2023/08/25*/ public interface Filter {Result invoke(final Invoker invoker, final Invocation invocation); } Invoker package com.xxx.arch.mw.…...
NX二次开发UF_CSYS_create_matrix 函数介绍
文章作者:里海 来源网站:https://blog.csdn.net/WangPaiFeiXingYuan UF_CSYS_create_matrix Defined in: uf_csys.h int UF_CSYS_create_matrix(const double matrix_values [ 9 ] , tag_t * matrix_id ) overview 概述 Creates a 3 x 3 matrix. 创建…...
css引入的三种方式
css引入的三种方式 一、内联样式二、外部样式表三、 内部样式表总结trouble 一、内联样式 内联样式也被称为行内样式。它是将 CSS 样式直接应用于 HTML 元素的 style 属性中的一种方式 <p style"color: blue; font-size: 16px;">这是一个带有内联样式的段落。&…...
含羞草研究所研究含羞草的代码
点击进入 一个简单的Python代码示例,用于模拟含羞草的行为: class Mimosa: def __init__(self): self.leaves_open True def touch_leaf(self): if self.leaves_open: print("Leaf closes due to touch.") self.leaves_open False else: p…...
常见立体几何图形的体积
文章目录 abstract祖暅原理推论 棱锥和圆锥的体积用积分的方法推导棱台和圆台的体积圆台体积公式 球体的体积球体的表面积 abstract 锥体和球体的体积公式主要通过积分的方法推导 这类公式的推导中学一般不要求,只要会应用公式在高等数学中由合适和方便的工具来推导这些公式而…...
vue3 + vue-router + keep-alive缓存页面
1.vue-router中增加mate.keepAlive和deepth属性 {path: /,name: home,component: HomeView,meta: {// 当前页面要不要缓存keepAlive: false,// 当前页面层级deepth: 1,}},{path: /list,name: list,component: ListView,meta: {// 当前页面要不要缓存keepAlive: true,// 当前页…...
unigui同页面内重定向跳转,企业微信内部应用开发获取用户code例子
procedure TMainForm.UniFormCreate(Sender: TObject); varurl: string;code: string; begin //如果没有code值,将进行重定向if UniApplication.Parameters.Values[code] thenbeginurl :https://open.weixin.qq.com/connect/oauth2/authorize?appid你们的企业ID&…...
垃圾数据啊
const arr [] //定义空数组 for (const key in this.fgkSyData) { //循环 this。sgksudata 数据arr.push( //push添加到 arr { [key]:this.fgkSyData[key] } //{} 在对象中 重新 定义key value 转换成对象) } console.log(arr, arr) …...
GB/T 29498-2013 木门窗检测
木门窗是指以木材、木质复合材料为主要材料制作框和扇的门窗。 GB/T 29498-2013 木门窗检测项目 测试项目 测试标准 外观质量 GB/T 29498 尺寸 GB/T 29498 装配质量 GB/T 29498 含水率 GB/T 17657 附着力 GB/T 4893.4 外门窗耐冷热循环 GB/T 4893.7 耐划痕 GB/…...
rocketMQ5.0顺序消息golang接入
本人理解,顺序消息如果不分消息组,那么会影响并行处理速度,所以尽量消息组分的散一些 首先上要求,官方文档如下: 总结: 1.必须同一个消息组,消息组和消费组不是一个概念,不要混 2.必…...
HuggingFace-利用BERT预训练模型实现中文情感分类(下游任务)
准备数据集 使用编码工具 首先需要加载编码工具,编码工具可以将抽象的文字转成数字,便于神经网络后续的处理,其代码如下: # 定义数据集 from transformers import BertTokenizer, BertModel, AdamW # 加载tokenizer token Ber…...
PSP - 从头搭建 抗原类别 (GPCR) 的 蛋白质结构预测 项目流程
欢迎关注我的CSDN:https://spike.blog.csdn.net/ 本文地址:https://spike.blog.csdn.net/article/details/134595717 GPCRs(G Protein-Coupled Receptors,G蛋白偶联受体),又称为7次跨膜受体,是细…...
城市NOA加速落地,景联文科技高质量数据标注助力感知系统升级
当前,自动驾驶技术的演进正在经历着从基础L2到L3过渡的重要阶段,其中NOA(自动辅助导航驾驶)扮演着至关重要的角色。城市NOA(L2.9)作为城市场景下的NOA,被看作是车企向更高阶自动驾驶迈进的必经之…...
控制反转(IoC)是什么?
文章目录 控制反转(Inversion of Control,IoC)传统的程序设计中:应用程序控制程序流程控制反转设计中:由框架或容器控制程序流程IoC 的作用 举例生活例子软件工程例子 控制反转(Inversion of Control&#…...
Redisson分布式锁源码解析、集群环境存在的问题
一、使用Redisson步骤 Redisson各个锁基本所用Redisson各个锁基本所用Redisson各个锁基本所用 二、源码解析 lock锁 1) 基本思想: lock有两种方法 一种是空参 另一种是带参 * 空参方法:会默认调用看门狗的过期时间30*1000&…...
2016年10月4日 Go生态洞察:HTTP追踪介绍
🌷🍁 博主猫头虎(🐅🐾)带您 Go to New World✨🍁 🦄 博客首页——🐅🐾猫头虎的博客🎐 🐳 《面试题大全专栏》 🦕 文章图文…...
分布式篇---第四篇
系列文章目录 文章目录 系列文章目录前言一、分布式ID生成有几种方案?二、幂等解决方法有哪些?三、常见负载均衡算法有哪些?前言 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给…...
从零开始的C++(十九)
红黑树: 一种接近平衡的二叉树,平衡程度低于搜索二叉树。 特点: 1.根节点为黑 2.黑色结点的子结点可以是红色结点或黑色结点。 3.红色结点的子结点只能是黑色结点。 4.每个结点到其所有叶子结点的路径的黑色结点个数相同。 5.指向空的…...
opencv-使用 Haar 分类器进行面部检测
Haar 分类器是一种用于对象检测的方法,最常见的应用之一是面部检测。Haar 分类器基于Haar-like 特征,这些特征可以通过计算图像中的积分图来高效地计算。 在OpenCV中,Haar 分类器被广泛用于面部检测。以下是一个简单的使用OpenCV进行面部检测…...
C++纯虚函数和抽象类 制作饮品案例(涉及知识点:继承,多态,实例化继承抽象类的子类,多文件实现项目)
一.纯虚函数的由来 在多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容。例如: #include<iostream>using namespace std;class AbstractCalculator { public:int m_Num1;int m_Num2;virtual int getResult(){r…...
简易版抽奖活动的设计技术方案
1.前言 本技术方案旨在设计一套完整且可靠的抽奖活动逻辑,确保抽奖活动能够公平、公正、公开地进行,同时满足高并发访问、数据安全存储与高效处理等需求,为用户提供流畅的抽奖体验,助力业务顺利开展。本方案将涵盖抽奖活动的整体架构设计、核心流程逻辑、关键功能实现以及…...
Unity3D中Gfx.WaitForPresent优化方案
前言 在Unity中,Gfx.WaitForPresent占用CPU过高通常表示主线程在等待GPU完成渲染(即CPU被阻塞),这表明存在GPU瓶颈或垂直同步/帧率设置问题。以下是系统的优化方案: 对惹,这里有一个游戏开发交流小组&…...
中南大学无人机智能体的全面评估!BEDI:用于评估无人机上具身智能体的综合性基准测试
作者:Mingning Guo, Mengwei Wu, Jiarun He, Shaoxian Li, Haifeng Li, Chao Tao单位:中南大学地球科学与信息物理学院论文标题:BEDI: A Comprehensive Benchmark for Evaluating Embodied Agents on UAVs论文链接:https://arxiv.…...
Java - Mysql数据类型对应
Mysql数据类型java数据类型备注整型INT/INTEGERint / java.lang.Integer–BIGINTlong/java.lang.Long–––浮点型FLOATfloat/java.lang.FloatDOUBLEdouble/java.lang.Double–DECIMAL/NUMERICjava.math.BigDecimal字符串型CHARjava.lang.String固定长度字符串VARCHARjava.lang…...
【RockeMQ】第2节|RocketMQ快速实战以及核⼼概念详解(二)
升级Dledger高可用集群 一、主从架构的不足与Dledger的定位 主从架构缺陷 数据备份依赖Slave节点,但无自动故障转移能力,Master宕机后需人工切换,期间消息可能无法读取。Slave仅存储数据,无法主动升级为Master响应请求ÿ…...
鸿蒙DevEco Studio HarmonyOS 5跑酷小游戏实现指南
1. 项目概述 本跑酷小游戏基于鸿蒙HarmonyOS 5开发,使用DevEco Studio作为开发工具,采用Java语言实现,包含角色控制、障碍物生成和分数计算系统。 2. 项目结构 /src/main/java/com/example/runner/├── MainAbilitySlice.java // 主界…...
Android第十三次面试总结(四大 组件基础)
Activity生命周期和四大启动模式详解 一、Activity 生命周期 Activity 的生命周期由一系列回调方法组成,用于管理其创建、可见性、焦点和销毁过程。以下是核心方法及其调用时机: onCreate() 调用时机:Activity 首次创建时调用。…...
LangChain【6】之输出解析器:结构化LLM响应的关键工具
文章目录 一 LangChain输出解析器概述1.1 什么是输出解析器?1.2 主要功能与工作原理1.3 常用解析器类型 二 主要输出解析器类型2.1 Pydantic/Json输出解析器2.2 结构化输出解析器2.3 列表解析器2.4 日期解析器2.5 Json输出解析器2.6 xml输出解析器 三 高级使用技巧3…...
Pandas 可视化集成:数据科学家的高效绘图指南
为什么选择 Pandas 进行数据可视化? 在数据科学和分析领域,可视化是理解数据、发现模式和传达见解的关键步骤。Python 生态系统提供了多种可视化工具,如 Matplotlib、Seaborn、Plotly 等,但 Pandas 内置的可视化功能因其与数据结…...
【Docker 02】Docker 安装
🌈 一、各版本的平台支持情况 ⭐ 1. Server 版本 Server 版本的 Docker 就只有个命令行,没有界面。 Platformx86_64 / amd64arm64 / aarch64arm(32 - bit)s390xCentOs√√Debian√√√Fedora√√Raspbian√RHEL√SLES√Ubuntu√√√√Binaries√√√ …...
