hiberna-validator 首次调用性能优化

 

spring集成hibernate-validator后,使用校验器第一次进行校验时,由于需要初始化导致第一次调用耗时过长,rpc中校验很可能导致调用超时,所以下面使用启动时初始化来解决

spring集成hibernate-validator配置:

 
        
        
        
    

 

扫描路径下的class ,启动时执行初始化方法

  /**
     * jsr-349校验器
     */
    @Autowired
    private LocalValidatorFactoryBean localValidatorFactoryBean;



/**
     * valid预加载
     */
    @PostConstruct
    public void valideBoost(){
        scanFrom("需要扫描的包名");
        scanFrom("com.xxx.order.trade.export.req");

    }

    /**
     * 启动加速!!!
     * @param basePackage
     */
    private void scanFrom(String basePackage){
        int count=0;
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        final String resourcePattern = "/**/*.class";
        String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(basePackage)
                + resourcePattern;
        try {
            Resource[] resources = resourcePatternResolver.getResources(pattern);
            MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader reader = readerFactory.getMetadataReader(resource);
                    //扫描到的class
                    String className = reader.getClassMetadata().getClassName();
                    Class clazz = Class.forName(className);
                    localValidatorFactoryBean.getConstraintsForClass(clazz);
                    count++;
                }
            }
        } catch (Exception e) {
            log.error("扫描包异常basePackage:{},e:{}",basePackage,e);
        }
        log.info("validator预加载:package:{},总数:{}",basePackage,count);
    }

 

你可能感兴趣的:(java网络编程,java)