常用配置随笔记

这篇博客主要记录了Springboot V2.3.4的相关配置,包括跨域访问处理、文件大小限制修改,以及Dockerfile和docker-compose的使用。此外,还涉及到了Mybatis_Plus的详细配置,如时间戳、乐观锁、分页插件和逻辑删除。同时,提到了Java后端部署于Linux的方法以及Swagger2和lelettuce(Jedis)的配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常用的配置就记录在下面,以后也省得找了
以后看到了配置的东西就记录在这里了

Springboot V2.3.4

跨域访问的后端处理

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        /**
         *  1 与访问路径
         *  2 请求来源
         *  3 允许跨域方法
         *  4 允许携带信息
         *  5 最大响应时间
         */
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

文件大小限制修改

  • 在application.yml增加如下配置
spring:
  servlet:
    multipart:
      max-file-size: 50MB
      max-request-size: 50MB
  • 在主启动类增加如下代码
@Configuration
@SpringBootApplication
public class PatmanageApplication {
    public static void main(String[] args) {
        SpringApplication.run(PatmanageApplication.class, args);
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //文件最大50M,DataUnit提供5中类型B,KB,MB,GB,TB
        factory.setMaxFileSize(DataSize.of(50, DataUnit.MEGABYTES));
        /// 设置总上传数据总大小50M
        factory.setMaxRequestSize(DataSize.of(50, DataUnit.MEGABYTES));
        return factory.createMultipartConfig();
    }
}

log4j

  • springboot中是默认logback的,先放到这里,万一以后会用呢
    log4j.properties 文件
	#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
	log4j.rootLogger=DEBUG,console,file
	
	#控制台输出的相关设置
	log4j.appender.console = org.apache.log4j.ConsoleAppender
	log4j.appender.console.Target = System.out
	log4j.appender.console.Threshold=DEBUG
	log4j.appender.console.layout = org.apache.log4j.PatternLayout
	log4j.appender.console.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH:mm:ss}][%c]-%m%n
	
	#文件输出的相关设置
	log4j.appender.file = org.apache.log4j.RollingFileAppender
	log4j.appender.file.File=./log/paleatta.log
	log4j.appender.file.MaxFileSize=10mb
	log4j.appender.file.Threshold=DEBUG
	log4j.appender.file.layout=org.apache.log4j.PatternLayout
	log4j.appender.file.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH:mm:ss}][%c]%m%n
	
	#日志输出级别
	log4j.logger.org.mybatis=DEBUG
	log4j.logger.java.sql=DEBUG
	log4j.logger.java.sql.Statement=DEBUG
	log4j.logger.java.sql.ResultSet=DEBUG
	log4j.logger.java.sql.PreparedStatement=DEBUG


#------------------------------------------------------------------------
#    %m 输出代码中指定的消息 
#    %p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL 
#    %r 输出自应用启动到输出该log信息耗费的毫秒数 
#    %c 输出所属的类目,通常就是所在类的全名 
#    %t 输出产生该日志事件的线程名 
#    %n 输出一个回车换行符,Windows平台为“rn”,Unix平台为“n” 
#    %d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyyy MMM dd HH:mm:ss,SSS},输出类似:2002年10月18日 :10:28,921
#    %l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。
#    %x Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event
#    %X Used to output the MDC (mapped diagnostic context) associated with the thread that generated the logging event for specified key
#------------------------------------------------------------------------

简易fastDFS配置类

		fastdfs.connect_timeout_in_seconds = 5
		fastdfs.network_timeout_in_seconds = 30
		fastdfs.charset = UTF-8
		fastdfs.tracker_servers = 101.132.32.165:22122

Vue引入组件Elementui,iconfont(阿里矢量图标)和axios

//引入elementui
import './plugins/element.js'

//搭配如iconfont样式
import './assets/loginImg/iconfont.css'

//导入axios
import axios from "axios";

//将Axios进行全局挂载
Vue.prototype.$http =axios

// 设置访问根路径
axios.defaults.baseURL="http://localhost:8080"

java后端部署Linux

Dockerfile

#jdk版本
FROM java:8
#后端暴露端口号
EXPOSE 8081
#运行jar包
ADD manage-0.0.1-SNAPSHOT.jar app.jar
RUN bash -c 'touch /app. jar'
ENTRYPOINT ["java", "-jar", "/app.jar","--spring.profiles.active=pro"]
#运行环境配置 走application-pro.yaml文件

docker-compose

version: "3"
services:
  nginx:
    image: nginx:latest
    ports:
    # 映射端口:实际nginx在容器中的运行端口
      - 8080:8080
    volumes:
      #   前端打包文件所在位置:实际nginx在容器中的运行端口
      - /root/labinfo/nginx/html:/usr/share/nginx/html
      #   nginx配置文件所在位置:实际nginx在容器中的运行端口
      - /root/labinfo/nginx/nginx.conf:/etc/nginx/nginx.conf
    privileged: true #解决nginx的文件调用权限问题
  mysql:
    image: mysql:5.7
    ports:
    # 映射端口:实际端口
      - 3307:3306
    environment:
      - MYSQL_ROOT_PASSWORD=123456
  patmanage:
    image: patmanage:latest
    build: . #表示以当前目录下的Dockerfile开始构建镜像
    ports:
    # 后端部署端口
      - 8081:8081
    depends_on:
      - mysql

Mybatis_Plus V3.4.1

增加时间戳

  • 以后可以不一定要添加时间,添加字符串什么的也可以
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;

@Slf4j
@Component
 public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

乐观锁配置

搭配@Version就可以使用了

@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor optimisticLockerInnerInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

分页插件配置

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,
     * 需要设置 MybatisConfiguration#useDeprecatedExecutor = false
     * 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new
                PaginationInnerInterceptor(DbType.MYSQL));
                //DbType后面要对应上自己的所连接的数据库的类型,不一定要是MYSQL
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }

逻辑删除配置

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: deleted  # 全局逻辑删除的实体字段名
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
@TableLogic
private Integer deleted

自动代码生成器

  • 代码生成器按需使用,根据自己的情况进行更改,最后再运行一下main就可以了
  • 最后不要忘记加上最后的配置
package com.paleatta.mybatisplus;


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;

/**
 * @description: 代码自动生成器
 * @program: mybatisplus
 * @author: paleatta
 * @date: 2020-12-28 15:08
 * @version: jdk1.8
 **/
// 执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {

    public static void main(String[] args) {
// 需要构建一个 代码自动生成器 对象
        AutoGenerator mpg = new AutoGenerator();
        // 配置策略
        // 1、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");//设置输出文件夹
        gc.setAuthor("paleatta");
        gc.setOpen(false);//是否打开文件夹
        gc.setFileOverride(false); // 是否覆盖
        gc.setServiceName("%sService"); // 去Service的I前缀
        gc.setIdType(IdType.ASSIGN_ID);//设置主键唯一策略
        gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
        gc.setSwagger2(true); //是否使用swagger2
        mpg.setGlobalConfig(gc);
        //2、设置数据源
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");//驱动器
        dsc.setUsername("root");//账号
        dsc.setPassword("123456");//密码
        dsc.setDbType(DbType.MYSQL);//数据库类型
        mpg.setDataSource(dsc);
        //3、包的配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("mybatisplus");//模块的名称
        pc.setParent("com.paleatta");//在哪个包下
        pc.setEntity("pojo");//实体类包名
        pc.setMapper("mapper");//Dao层包名
        pc.setService("service");//service层包名
        pc.setController("controller");//controller层包名
        mpg.setPackageInfo(pc);
        //4、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("user", "user1"); // 设置要映射的数据库的表名
        strategy.setNaming(NamingStrategy.underline_to_camel);//支持下划线转驼峰
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//支持下划线转驼峰
        strategy.setEntityLombokModel(true); // 自动lombok;
        strategy.setLogicDeleteFieldName("deleted");//设置逻辑删除标志
        // 自动填充配置
        //	这里是自动对创建时间和更新时间进行配置
        //  gmt_create  gmt_modified 国际通用创建时间和更新时间
        TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
        TableFill updateTime = new TableFill("update_time",
                FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(createTime);
        tableFills.add(updateTime);
        strategy.setTableFillList(tableFills);
        // 乐观锁
        strategy.setVersionFieldName("version");//乐观锁标志位
        strategy.setRestControllerStyle(true);//restful风格设置
        strategy.setControllerMappingHyphenStyle(true);//驼峰转连字符,我也不太懂啥意思
        //localhost:8080/hello_id_2
        mpg.setStrategy(strategy);
        mpg.execute(); //执行
    }
}
<!-- 代码自动生成器的maven配置  -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.1</version>
</dependency>
<!-- 设置为默认风格 -->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.2</version>
</dependency>
<!-- 下面两个是swagger2的maven配置 不用的话可以不配置 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- 目前感觉没啥用 -->
<!-- https://mvnrepository.com/artifact/io.swagger.core.v3/swagger-annotations -->
<dependency>
    <groupId>io.swagger.core.v3</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>2.1.5</version>
</dependency>

Swagger2 v2.9.2

@Configuration
@EnableSwagger2
public class swaggerConfig {
    @Bean
    public Docket docket(Environment environment) {
        Profiles profiles = Profiles.of("dev");
        boolean flag = environment.acceptsProfiles(profiles);
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("paleatta")
                .apiInfo(apiInfo())
                //是否启用swagger
                //通过在何种环境下来决定是否启用swagger
                .enable(flag)
                .select()
                //设置要扫描所有的包
                //.apis(RequestHandlerSelectors.any())
                //所有的包都不扫描
                //.apis(RequestHandlerSelectors.none())
                //扫描类注解为RestController的类
                //.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                //扫描方法注解为RequestMapping的方法
                //.apis(RequestHandlerSelectors.withMethodAnnotation(RequestMapping.class))
                //扫描指定包 常用
                .apis(RequestHandlerSelectors.basePackage("com.paleatta.swagger.controller"))
                //过滤器,只扫描接口的第一路径为paleatta的路径
//                .paths(PathSelectors.ant("/paleatta/**"))
                .build()
                ;
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("paleatta", "http://localhost:8080/", "123456789@qq.com");

        return new ApiInfo(
                "Swagger练习API",
                "技术宅拯救世界",
                "1.0bate",
                "http://101.132.32.165:7215/",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>());
    }
}

lelettuce(Jedis)

  • lelettuce json序列化配置
@Configuration
public class RedisConfig {
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory
factory) {
// 我们为了自己开发方便,一般直接使用 <String, Object>
RedisTemplate<String, Object> template = new RedisTemplate<String,
Object>();
template.setConnectionFactory(factory);
// Json序列化配置
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new
Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// String 的序列化
StringRedisSerializer stringRedisSerializer = new
StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值