设计模式

=> 状态模式

context实现state,并通过管理实现类重载方法

数据结构

=> DTO数据结构

应具备多种字段的of创建功能
可使用内部类维护值枚举

=> 緩存術

  1. redis map
  2. 分段锁

=> 使用init标志位标识初始化,而非某字段为空

if (!init) {
    init();
}

工具类

=> check int

StringUtils::isNumeric

=> hash

Objects.hash
Arrays.hashCode

=> 枚举容器

enum::static class 维护内部容器

=> swagger

@Bean
public Docket defaultApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .useDefaultResponseMessages(false)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.controller"))
            .paths(PathSelectors.any())
            .build();
}

=> baiji参数校验器

extends AbstractBaijiValidator<UserAddOrUpdateRequest> 

public UserAddOrUpdateRequestValidator() {
    super(UserAddOrUpdateRequest.class);
    ruleFor("usersAddOrUpdate").notNull();
    ruleFor("currentUserNo").notNull().notEmpty();
    ruleFor("usersAddOrUpdate").setCollectionValidator(new UsersAddOrUpdateValidator());
}

=> 注解添加约束器

为注解添加@Constraint

implements ConstraintValidator<注解, Object>

@Override
public void initialize(Pagination constraintAnnotation) {

@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {

=> 属性校验器

AbstractValidator
ruleFor("city").notNull().setValidator(new PropertyValidator("CityId can not be null") {
        @Override
        protected boolean isValid(PropertyValidatorContext context) {

=> 属性比较

Objects类:例Objects.equals(A,B)

=> 参数校验

Preconditions.checkArgument

反射AOP

=> Bean属性<->Map

    Map<String, Object> beanMap = Maps.newHashMap();
    if (bean != null) {
        BeanMap tempMap = BeanMap.create(bean);
        for (Object key : tempMap.keySet()) {
            String putKey = String.valueOf(key);
            Object putValue = tempMap.get(key);
            beanMap.put(putKey, putValue);
        }
    }    
    
    BeanMap tempMap = BeanMap.create(bean);
    tempMap.putAll(beanMap);

=> 反射获取属性

for (Field field : fields) {
        TitleName name = field.getDeclaredAnnotation(TitleName.class);
        if(name != null) {
            title.add(name.value());
        }else {
            title.add(field.getName());
        }
    }
    
  ReflectionUtils.doWithFields(obj.getClass(), (field) -> {
            ReflectionUtils.makeAccessible(field);
            if(field.get(obj) == null) {
                values.add("");
            }else {
                values.add(String.valueOf(field.get(obj)));
            }
        });

=> 通过反射调用方法

Method statusTypeFieldMethod = ReflectionUtils.findMethod(response.getClass(), SET_STATUS_METHOD, ResponseStatusType.class);
ReflectionUtils.makeAccessible(statusTypeFieldMethod);
ReflectionUtils.invokeMethod(statusTypeFieldMethod, response, responseStatusType);

=> 通过注解反射提供属性

注解仅用于提供所需要的属性值,而非AOP进行处理

=> 反射拦截器

    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(Logger.class);
    enhancer.setCallback(new Interceptor(logger));
    
    private static class Interceptor implements MethodInterceptor

=> 反射代理

Class<?> targetClass = AopUtils.getTargetClass(bean);

if (AnnotationUtils.findAnnotation(targetClass, EnableValidation.class) != null) {

ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTargetClass(targetClass);
        proxyFactory.addAdvice(new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                //ignore checkHealth()
                if ("checkHealth".equals(invocation.getMethod().getName())) {
                    // do business logic.
                    Method method = invocation.getMethod();
                    return method.invoke(bean, invocation.getArguments());
                } else {
                    Object result = null;
                    try {
                        // Before: check request param
                        doPreHandle(invocation);
                        // do business logic.
                        Method method = invocation.getMethod();
                        result =  method.invoke(bean, invocation.getArguments());
                    } finally {
                        // After: handle the result after finish business logic.
                        doAfterHandle(result);
                    }
                    return result;
                }
            }
        });
        return proxyFactory.getProxy(ClassUtils.getDefaultClassLoader());

=> 注解内部属性

@interface Inner {
    Outer[] value();
}

并发控制

=> "同步->异步->同步"调用方式

  1. 信号量机制:使用{@code CountDownLatch}结合{@code Executor)
  2. 异步阻塞机制:使用{@code Future}进行集合join操作

=> map.computeIfAbsent

map.computeIfAbsent(key, k -> new Value(f(k)));

map.computeIfAbsent(key, k -> new HashSet<V>()).add(v);

API处理

=> 拦截器

HandlerInterceptorAdapter

SPRING

=> @Order注解

Order配合List注入

=> Bean装配

  1. 使用@Autowire直接注入List/Map

  2. 获取上下文

    implements ApplicationContextAware

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    applicationContext.getBeansOfType(.class)
    .values()
    .forEach(c -> CONVERTER_MAP.put(c.dataType(), c));
    }

    BaijiServletContext.INSTANCE.getApplicationContext().getBeansOfType(EventListener.class)

=> 装配完成后加载

implements BeanPostProcessor

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException  

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException 

为bean添加代理增强后返回bean 

消息队列

=> MQ消费者

@Autowired
private MessageConsumerProvider consumerProvider;

@PostConstruct
public void init() {
    this.rateLimiterKey = RateLimiterUtil.findRateLimiterKey(this.getClass());
    this.MessageChecking = this.getClass().isAnnotationPresent(MessageCheck.class);
    this.consumerProvider.addListener(this.subject(), this.group(), this::onMessage);
}

=> 通过注解限流

@UseRateLimiter("XXLimiter")

埋点监控

=> 线程初始化

private static final ThreadLocal<Map<TypeEnum, Map<String, String>>> CONTEXT = ThreadLocal.withInitial(
        () -> {
            Map<TypeEnum, Map<String, String>> map = new ConcurrentHashMap<>();
            map.put(TypeEnum.LOG_INDEX, new ConcurrentHashMap<>());
            map.put(TypeEnum.LOG_STORE, new ConcurrentHashMap<>());
            return map;
        }
);