package com.bohuikeji.delivery.backstage;

import com.alibaba.druid.pool.DruidDataSource;
import io.undertow.conduits.GzipStreamSourceConduit;
import io.undertow.server.handlers.encoding.RequestEncodingHandler;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.session.data.redis.config.ConfigureRedisAction;

import java.util.Properties;

/**
 * 启动类
 */
@SpringBootApplication(scanBasePackages ={"com.bohuikeji.frame.module.admin","com.bohuikeji.delivery.backstage"} )
@MapperScan("com.bohuikeji.delivery.backstage.mapper*")
@EnableCaching
public class Application {
    private final Environment env;

    public Application(Environment env) {
        this.env = env;
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        //初始化链接数量
        dataSource.setInitialSize(150);
        //最大链接数量
        dataSource.setMaxActive(6000);
        //允许的空闲连接
        dataSource.setMinIdle(150);
        //当链接不够时，druid的等待时间ms,超时抛出异常
        dataSource.setMaxWait(10000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setRemoveAbandoned(true);
        dataSource.setPoolPreparedStatements(false);
        dataSource.setRemoveAbandonedTimeout(180);
        dataSource.setLogAbandoned(false);
        Properties connP=dataSource.getConnectProperties();
        connP.setProperty("druid.mysql.usePingMethod","false");
        dataSource.setConnectProperties(connP);
        return dataSource;
    }
    @Bean
    public static ConfigureRedisAction configureRedisAction() {
        return ConfigureRedisAction.NO_OP;
    }
    @Bean
    public UndertowServletWebServerFactory undertowServletWebServerFactory() {
        UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
        factory.addDeploymentInfoCustomizers((deploymentInfo) -> {
            deploymentInfo.addInitialHandlerChainWrapper(handler -> new RequestEncodingHandler(handler)
                    .addEncoding("gzip", GzipStreamSourceConduit.WRAPPER));
        });
        return factory;
    }
}
