springboot(42) : 简单WEB服务

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xxx.test</groupId>
    <artifactId>my-test</artifactId>
    <version>1.0-SNAPSHOT</version>


    <properties>
        <java.version>1.8</java.version>
        <skipTests>true</skipTests>
        <druid-spring-boot.version>1.1.17</druid-spring-boot.version>
        <springboot-mybatis.version>1.3.2</springboot-mybatis.version>
        <mysql-jdbc.version>8.0.18</mysql-jdbc.version>
        <pagehelper-spring-boot.version>1.2.5</pagehelper-spring-boot.version>
        <springfox-swagger.version>2.9.2</springfox-swagger.version>
        <mapper-spring-boot.version>2.1.5</mapper-spring-boot.version>
        <mapstruct.version>1.4.2.Final</mapstruct.version>
        <aliyun-log-producer.version>0.3.0</aliyun-log-producer.version>
        <aliyun-log.version>0.6.33</aliyun-log.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.14</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.html</include>
                    <include>**/*.img</include>
                    <include>**/*.js</include>
                    <include>**/*.css</include>
                    <include>**/*.txt</include>
                    <include>**/*.woff</include>
                    <include>**/*.ttf</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.7.5</version>
                <configuration>
                    <!-- 指定该Main Class为全局的唯一入口 -->
                    <mainClass>com.xxx.Application</mainClass>
                    <layout>ZIP</layout>
                    <includeSystemScope>true</includeSystemScope><!-- 把第三方jar包打进去 -->
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中 -->
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

application.properties

# 版本
config.version=1.0
server.port=8080
spring.application.name=my-test

# 编码
spring.banner.charset=UTF-8
spring.messages.encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.force=true
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8

# 文件上传限制
spring.servlet.multipart.max-file-size=500MB
spring.servlet.multipart.max-request-size=500MB

logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <springProperty scope="context" name="appName" source="spring.application.name" defaultValue="spring.default.log"/>
    <springProperty scope="context" name="logFileDir" source="logging.path" defaultValue="logs"/>

    <!-- 目前约定profile:dev:开发, test:测试, produce:生产 -->

    <!-- 当前日志存放路径(路径末尾不要带“/”),设置默认值 -->
    <property name="LOG_FILE_DIR" value="${logFileDir}/${appName}"/>
    <!-- 历史归档日志存放路径(路径末尾不要带“/”),设置默认值 -->
    <property name="HIS_LOG_FILE_DIR" value="${logFileDir}/${appName}/history"/>

    <!-- You can override this to have a custom pattern -->
    <property name="CONSOLE_LOG_PATTERN"
              value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>

    <!-- Appender to log to console -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <!-- Minimum logging level to be presented in the console logs-->
            <level>DEBUG</level>
        </filter>
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>

    <!-- 文件输出 -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_FILE_DIR}/${appName}.log</file>
        <append>true</append>
        <!--定义日志滚动的策略-->
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- 日志最大的历史 30天 -->
            <maxHistory>30</maxHistory>
            <!--每个日志文件最大500MB-->
            <maxFileSize>500MB</maxFileSize>
            <!--用来指定日志文件的上限大小,那么到了这个值,就会删除旧的日志-->
            <totalSizeCap>20GB</totalSizeCap>
            <fileNamePattern>${HIS_LOG_FILE_DIR}/${appName}.%d{yyyy-MM-dd}.log.%i.gz</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS}|%level|%logger{36}:%line|%thread|%X{traceId}|%msg%n</pattern>
        </encoder>
    </appender>

    <appender name="asyncLoggerAppender" class="ch.qos.logback.classic.AsyncAppender">
        <!--定义了一个过滤器,在LEVEL之下的日志输出不会被打印出来-->
        <!--这里定义了INFO,也就是文件不会输出比INFO级别小的日志-->
        <!-- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
             <level>INFO</level>
         </filter>-->
        <discardingThreshold>0</discardingThreshold>
        <queueSize>1024</queueSize>
        <neverBlock>true</neverBlock>
        <appender-ref ref="FILE"/>
    </appender>

    <root level="INFO">
        <appender-ref ref="console"/>
        <appender-ref ref="asyncLoggerAppender"/>
    </root>
</configuration>

Application.java

package com.alibaba.gts.cdyj.event.push;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableScheduling;


@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class},
        scanBasePackages = {"com.xxx"})
@PropertySource(value = "classpath:application.properties", encoding = "utf-8")
@EnableScheduling
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

--- 以下可选

TestController.java

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @RequestMapping("/test/{type}")
    public Object test(@PathVariable("type") Integer type, String p1, String p2) {
        switch (type) {
            case 1:
            default:
                break;
        }
        return "SUCCESS";
    }
}

init.java


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Component
@Slf4j
public class Init implements CommandLineRunner {

    @Resource
    private ConfigurableEnvironment springEnv;

    @Autowired
    private EnvService envService;

    @Value("${spring.application.name:-}")
    private String applicationName;

    @Value("${server.port}")
    private Integer port;

    @Value("${config.version:-}")
    private String version;


    @Override
    public void run(String... args) throws Exception {
        log.info("【服务启动成功!】\n====> 运行端口:{}\n====> 版本:{}",
                port, version);
        setEnv();
    }

    public void setEnv() {
        MutablePropertySources propSrcs = springEnv.getPropertySources();
        // 获取所有配置
        Map<String, String> props = StreamSupport.stream(propSrcs.spliterator(), false)
                .filter(ps -> ps instanceof EnumerablePropertySource)
                .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
                .flatMap(Arrays::stream)
                .distinct()
                .collect(Collectors.toMap(Function.identity(), springEnv::getProperty));
        envService.set(props);
    }
}

EnvService.java


import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class EnvService {

    private Map<String, String> map;


    public void set(Map<String, String> map) {
        this.map = map;
    }

    public Map<String, String> getMap() {
        return map;
    }
}

EnvController.java


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EnvController {

    @Autowired
    private EnvService envService;

    @RequestMapping("/env")
    public Object env() {
        return envService.getMap();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值