sunrays-framework配置重构

文章目录

1.common-log4j2-starter

1.目录结构
2.Log4j2Properties.java 新增两个属性
java 复制代码
package com.sunxiansheng.log4j2.config.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Description: 日志切面配置
 *
 * @Author sun
 * @Create 2024/10/24 23:16
 * @Version 1.0
 */
@ConfigurationProperties(prefix = "sun-rays.log4j2")
@Data
public class Log4j2Properties {

    /**
     * 是否开启日志切面
     */
    private boolean logAspectEnable = true;

    /**
     * 日志存储根目录
     */
    private String home = "./logs";

    /**
     * 日志模块(从仓库中最顶级的模块开始) 例如:sunrays-framework/sunrays-demo/common-log4j2-starter-demo
     */
    private String module = "defaultModule";
}
3.Log4j2AutoConfiguration.java 条件注入LogAspect
java 复制代码
package com.sunxiansheng.log4j2.config;

import com.sunxiansheng.log4j2.aspectj.LogAspect;
import com.sunxiansheng.log4j2.config.properties.Log4j2Properties;
import com.sunxiansheng.log4j2.trace.TraceIdFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * Description: Log4j2自动配置类
 *
 * @Author sun
 * @Create 2024/10/24 10:36
 * @Version 1.0
 */
@Configuration
@EnableConfigurationProperties({Log4j2Properties.class}) // 启用配置类
@Slf4j
public class Log4j2AutoConfiguration {

    /**
     * 自动配置成功日志
     */
    @PostConstruct
    public void logConfigSuccess() {
        log.info("Log4j2AutoConfiguration has been loaded successfully!");
    }

    /**
     * 条件注入LogAspect
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "sun-rays.log4j2.log-aspect-enable", havingValue = "true", matchIfMissing = true)
    LogAspect logAspect() {
        log.info("LogAspect 成功注入!");
        return new LogAspect();
    }

    /**
     * 条件注入链路追踪过滤器
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    TraceIdFilter traceIdFilter() {
        return new TraceIdFilter();
    }
}
4.ApplicationEnvironmentPreparedListener.java 从Log4j2Properties.java中定义的配置读取信息
java 复制代码
package com.sunxiansheng.log4j2.listener;

import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.logging.LoggingApplicationListener;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * Description: 配置文件已加载,Environment 对象已初始化
 * 使用 ApplicationEnvironmentPreparedEvent 读取 application.yml 文件中的 sun-rays-log4j2.home 和 sun-rays-log4j2.module 配置
 *
 * @Author sun
 * @Create 2024/12/13 23:53
 * @Version 1.0
 */
public class ApplicationEnvironmentPreparedListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();

        // 获取 log.home 属性并提供默认值
        String logHome = environment.getProperty("sun-rays.log4j2.home", "./logs");
        if ("./logs".equals(logHome)) {
            System.err.println("WARNING: sun-rays.log4j2.home 属性未设置,使用默认值: " + logHome);
        }

        // 获取 log.module 属性并提供默认值
        String logModule = environment.getProperty("sun-rays.log4j2.module", "defaultModule");
        if ("defaultModule".equals(logModule)) {
            System.err.println("WARNING: sun-rays.log4j2.module 属性未设置,使用默认值: " + logModule);
        }

        // 将属性设置为系统属性
        System.setProperty("log.home", logHome);
        System.setProperty("log.module", logModule);
    }

    /**
     * 当前监听器的启动顺序需要在日志配置监听器的前面,保证在日志文件初始化之前读取 application.yml 的配置。
     *
     * @return
     */
    @Override
    public int getOrder() {
        return LoggingApplicationListener.DEFAULT_ORDER - 1;
    }
}

2.common-minio-starter

1.MinioProperties.java
java 复制代码
package com.sunxiansheng.minio.config.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Description: Minio配置
 *
 * @Author sun
 * @Create 2024/11/12 23:15
 * @Version 1.0
 */
@ConfigurationProperties(prefix = "sun-rays.minio")
@Data
public class MinioProperties {

    /**
     * minio服务地址
     */
    private String endpoint;
    /**
     * minio服务用户名
     */
    private String accessKey;
    /**
     * minio服务密码
     */
    private String secretKey;
}

3.common-mybatis-plus-starter

1.目录结构
2.BaseEntity.java
java 复制代码
package com.sunxiansheng.mybatis.plus.base.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import lombok.*;

import java.io.Serializable;
import java.util.Date;

/**
 * Description: Entity基类
 *
 * @Author sun
 * @Create 2024/10/26 10:35
 * @Version 1.0
 */
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class BaseEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 创建者
     */
    @TableField("create_by")  // 数据库中的字段名
    private String createBy;

    /**
     * 创建时间
     */
    @TableField("create_time")  // 数据库中的字段名
    private Date createTime;

    /**
     * 更新者
     */
    @TableField("update_by")  // 数据库中的字段名
    private String updateBy;

    /**
     * 更新时间
     */
    @TableField("update_time")  // 数据库中的字段名
    private Date updateTime;
}
3.SunRaysBaseServiceImpl.java 删除掉事务注解
java 复制代码
package com.sunxiansheng.mybatis.plus.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sunxiansheng.mybatis.plus.base.service.SunRaysBaseService;

import java.io.Serializable;
import java.util.List;

/**
 * Description: SunRays-Framework 基础Service实现类
 *
 * @Author sun
 * @Create 2024/10/25 17:38
 * @Version 1.0
 */
public class SunRaysBaseServiceImpl<M extends BaseMapper<T>, T, ID extends Serializable>
        implements SunRaysBaseService<T, ID> {

    // Mapper字段,私有化处理,不允许子类直接访问,只能通过Setter注入
    private M mybatisPlusMapper;

    // Setter方法用于注入MyBatis-Plus Mapper
    public void setMybatisPlusMapper(M mybatisPlusMapper) {
        this.mybatisPlusMapper = mybatisPlusMapper;
    }

    // ============================== 基于事务的CRUD方法 ==============================

    @Override
    public boolean existsById(ID id) {
        T t = mybatisPlusMapper.selectById(id);
        return t != null;
    }

    @Override
    public boolean exists(T po) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>(po);
        return mybatisPlusMapper.exists(queryWrapper);
    }

    @Override
    public Long count(T po) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>(po);
        return mybatisPlusMapper.selectCount(queryWrapper);
    }

    @Override
    public T listById(ID id) {
        return mybatisPlusMapper.selectById(id);
    }

    @Override
    public T listOne(T po) {
        return mybatisPlusMapper.selectOne(new QueryWrapper<>(po));
    }

    @Override
    public List<T> listAll(T po) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>(po);
        return mybatisPlusMapper.selectList(queryWrapper);
    }

    @Override
    public int insertOne(T po) {
        return mybatisPlusMapper.insert(po);
    }

    @Override
    public int updateById(T po) {
        return mybatisPlusMapper.updateById(po);
    }

    @Override
    public int update(T po, T condition) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>(condition);
        return mybatisPlusMapper.update(po, queryWrapper);
    }

    @Override
    public int deleteById(ID id) {
        return mybatisPlusMapper.deleteById(id);
    }

    @Override
    public int deleteBatchByIds(List<ID> ids) {
        return mybatisPlusMapper.deleteBatchIds(ids);
    }

    @Override
    public int delete(T po) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>(po);
        return mybatisPlusMapper.delete(queryWrapper);
    }
}
4.MyBatisPlusProperties.java 统一配置
java 复制代码
package com.sunxiansheng.mybatis.plus.config.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Description: MyBatisPlus配置
 *
 * @Author sun
 * @Create 2025/1/3 21:36
 * @Version 1.0
 */
@ConfigurationProperties(prefix = "sun-rays.mybatis-plus")
@Data
public class MyBatisPlusProperties {

    /**
     * 是否启用sql美化
     */
    private boolean sqlBeautyEnabled = true;
}
5.MybatisPLusAutoConfiguration.java
java 复制代码
package com.sunxiansheng.mybatis.plus.config;

import com.sunxiansheng.mybatis.plus.config.properties.MyBatisPlusProperties;
import com.sunxiansheng.mybatis.plus.interceptor.SqlBeautyInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * Description: MybatisPLus自动配置类
 *
 * @Author sun
 * @Create 2024/10/23 23:00
 * @Version 1.0
 */
@Configuration
@EnableConfigurationProperties({MyBatisPlusProperties.class}) // 启用配置类
@Slf4j
public class MybatisPLusAutoConfiguration {

    /**
     * 自动配置成功日志
     */
    @PostConstruct
    public void logConfigSuccess() {
        log.info("MybatisPLusAutoConfiguration has been loaded successfully!");
    }

    /**
     * SQL美化拦截器
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "sun-rays.mybatis-plus", value = "sql-beauty-enabled", havingValue = "true", matchIfMissing = true)
    public SqlBeautyInterceptor sqlBeautyInterceptor() {
        log.info("SqlBeautyInterceptor 成功注入!");
        return new SqlBeautyInterceptor();
    }
}
6.application.yml 提供通用配置
yaml 复制代码
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource # druid连接池
    druid:
      initial-size: 10          # 初始化连接数(适当减少以节省资源)
      min-idle: 10              # 最小空闲连接数
      max-active: 50            # 最大连接数(根据业务需求调整)
      max-wait: 30000           # 获取连接的最大等待时间(30秒)
      timeBetweenEvictionRunsMillis: 60000  # 每60秒检查一次空闲连接
      minEvictableIdleTimeMillis: 300000    # 最小空闲时间5分钟后回收
      testWhileIdle: true       # 检查空闲连接是否可用
      testOnBorrow: true        # 检查从连接池获取的连接是否可用
      removeAbandoned: true     # 启用清理超时连接
      removeAbandonedTimeout: 180  # 连接超时时间180秒
      logAbandoned: true        # 记录被清理的连接日志
7.pom.xml 排除logging
xml 复制代码
<!-- jdbc -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>spring-boot-starter-logging</artifactId>
            <groupId>org.springframework.boot</groupId>
        </exclusion>
    </exclusions>
</dependency>

4.common-openai-starter-demo

1.目录结构
2.OpenAiProperties.java
java 复制代码
package com.sunxiansheng.openai.config.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Description: OpenAI配置属性类
 *
 * @Author sun
 * @Create 2024/12/14 11:44
 * @Version 1.0
 */
@Data
@ConfigurationProperties(prefix = "sun-rays.openai")
public class OpenAiProperties {

    /**
     * OpenAI API Key
     */
    private String apiKey;

    /**
     * OpenAI API URL 有默认值
     */
    private String apiUrl = "https://api.openai.com/v1/chat/completions";
}
相关推荐
苏-言16 分钟前
SSM框架探秘:Spring 整合 Mybatis 框架
java·spring·mybatis
qq_447663051 小时前
java-----多线程
java·开发语言
a辰龙a1 小时前
【Java报错解决】警告: 源发行版 11 需要目标发行版 11
java·开发语言
听海边涛声1 小时前
JDK长期支持版本(LTS)
java·开发语言
IpdataCloud1 小时前
Java 获取本机 IP 地址的方法
java·开发语言·tcp/ip
MyMyMing1 小时前
Java的输入和输出
java·开发语言
忆~遂愿1 小时前
3大关键点教你用Java和Spring Boot快速构建微服务架构:从零开发到高效服务注册与发现的逆袭之路
java·人工智能·spring boot·深度学习·机器学习·spring cloud·eureka
云夏之末1 小时前
【Java报错已解决】java.lang.UnsatisfiedLinkError
java·开发语言
计算机-秋大田2 小时前
基于SpringBoot的假期周边游平台的设计与实现(源码+SQL脚本+LW+部署讲解等)
java·vue.js·spring boot·后端·课程设计
麻辣香蝈蝈2 小时前
【Java】微服务找不到问题记录can not find user-service
java·微服务·nacos