常见工具类

常见工具类

底层代码生成器

/**
 * 底层代码生成器
 *
 * @author 石一歌
 * @date 2022-07-07 22:02
 */
public class EntityUtil {
    private static final String PROJECT_NAME = "search";

    private static final String MODULE_NAME = "search";

    private static final String USER = "root";

    private static final String PASSWORD = "root";

    private static final String BASE_FILE_PATH = System.getProperty("user.dir");

    private static final String TYPE_CHAR = "char";

    private static final String TYPE_DATE = "date";

    private static final String TYPE_TIMESTAMP = "timestamp";

    private static final String TYPE_INT = "int";

    private static final String TYPE_BIGINT = "bigint";

    private static final String TYPE_TEXT = "text";

    private static final String TYPE_BIT = "bit";

    private static final String TYPE_DECIMAL = "decimal";

    private static final String TYPE_BLOB = "blob";

    private static final String BEAN_PATH = BASE_FILE_PATH + "\\src\\main\\java\\";

    private static final String MAPPER_PATH = BASE_FILE_PATH + "\\src\\main\\java\\com\\bmw\\" + PROJECT_NAME + "\\dao";

    private static final String XML_PATH = BASE_FILE_PATH + "\\src\\main\\resources\\mapping";

    private static final String MODEL_PACKAGE = "com.bmw." + PROJECT_NAME + ".model";

    private static final String DAO_PACKAGE = "com.bmw." + PROJECT_NAME + ".dao";

    private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";

    private static final String URL = "jdbc:mysql://127.0.0.1:3306/" + MODULE_NAME
            + "?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2b8";

    private String tableName = null;

    private String beanName = null;

    private String mapperName = null;

    private Connection conn = null;


    public static String createPackagePath(String packageName) {
        StringBuilder sbBuffer = new StringBuilder();
        String[] arrays = packageName.split("\\.");
        for (String str : arrays) {
            sbBuffer.append(str).append(File.separator);
        }
        return sbBuffer.toString();
    }

    public static void main(String[] args) {
        try {
            new EntityUtil().generate();
        } catch (ClassNotFoundException | SQLException | IOException e) {
            e.printStackTrace();
        }
    }

    private void init() throws ClassNotFoundException, SQLException {
        Class.forName(DRIVER_NAME);
        conn = DriverManager.getConnection(URL, USER, PASSWORD);
    }

    /**
     * 获取所有的表
     *
     * @return java.util.List<java.lang.String>
     * @author 石一歌
     * @date 2022/7/7 22:50
     */
    private List<String> getTables() throws SQLException {
        List<String> tables = new ArrayList<>();
        PreparedStatement pState = conn.prepareStatement("show tables");
        ResultSet results = pState.executeQuery();
        while (results.next()) {
            String tableName = results.getString(1);
            tables.add(tableName);
        }
        return tables;
    }

    private void processTable(String table) {
        StringBuilder sb = new StringBuilder(table.length());
        String tableNew = table.toLowerCase();
        String[] tables = tableNew.split("_");
        String temp;
        for (String s : tables) {
            temp = s.trim();
            sb.append(temp.substring(0, 1).toUpperCase()).append(temp.substring(1));
        }
        beanName = sb.toString();
        mapperName = beanName;
    }

    private Set<String> processImportType(List<String> columns, List<String> types) {
        Set<String> set = new HashSet<>();
        for (int i = 0; i < columns.size(); i++) {
            String type = types.get(i);
            if (type.contains(TYPE_DATE)) {
                set.add("import java.util.Date;");
            } else if (type.contains(TYPE_TIMESTAMP)) {
                set.add("import java.util.Date;");
            } else if (type.contains(TYPE_DECIMAL)) {
                set.add("import java.math.BigDecimal;");
            }
        }
        return set;
    }

    private String processType(String type) {
        if (type.contains(TYPE_CHAR)) {
            return "String";
        } else if (type.contains(TYPE_BIGINT)) {
            return "Long";
        } else if (type.contains(TYPE_INT)) {
            return "Integer";
        } else if (type.contains(TYPE_DATE)) {
            return "Date";
        } else if (type.contains(TYPE_TEXT)) {
            return "String";
        } else if (type.contains(TYPE_TIMESTAMP)) {
            return "Date";
        } else if (type.contains(TYPE_BIT)) {
            return "Boolean";
        } else if (type.contains(TYPE_DECIMAL)) {
            return "BigDecimal";
        } else if (type.contains(TYPE_BLOB)) {
            return "byte[]";
        }
        return null;
    }

    private boolean processTypeIfCase(String type) {
        if (type.contains(TYPE_CHAR)) {
            return true;
        } else {
            return type.contains(TYPE_TEXT);
        }
    }

    private String processField(String field) {
        String s = "__";
        System.out.println(field + "!!!!!!!");
        StringBuilder sb = new StringBuilder(field.length());
        if (field.contains(s)) {
            return field;
        }
        String[] fields = field.split("_");
        String temp;
        sb.append(fields[0]);
        for (int i = 1; i < fields.length; i++) {
            temp = fields[i].trim();
            sb.append(temp.substring(0, 1).toUpperCase()).append(temp.substring(1));
        }
        return sb.toString();
    }

    /**
     * 构建类上面的注释
     *
     * @param bw   輸出
     * @param text 内容
     * @author 石一歌
     * @date 2022/7/7 23:00
     */
    private void buildClassComment(BufferedWriter bw, String text) throws IOException {
        bw.newLine();
        bw.newLine();
        bw.write("/**");
        bw.newLine();
        bw.write(" * ");
        bw.newLine();
        bw.write(" * " + text);
        bw.newLine();
        bw.write(" * ");
        bw.newLine();
        bw.write(" **/");
    }

    /**
     * 构建方法上面的注释
     *
     * @param bw   输出
     * @param text 内容
     * @author 石一歌
     * @date 2022/7/7 23:02
     */
    private void buildMethodComment(BufferedWriter bw, String text) throws IOException {
        bw.newLine();
        bw.write("\t/**");
        bw.newLine();
        bw.write("\t * ");
        bw.newLine();
        bw.write("\t * " + text);
        bw.newLine();
        bw.write("\t * ");
        bw.newLine();
        bw.write("\t **/");
    }

    /**
     * 生成实体类
     *
     * @param columns      列
     * @param types        类型
     * @param comments     注释
     * @param tableComment 表注释
     * @author 石一歌
     * @date 2022/7/7 23:02
     */
    private void buildEntityBean(List<String> columns, List<String> types, List<String> comments,
                                 String tableComment) throws IOException {
        // 创建包目录
        String packagePath = BEAN_PATH + File.separator + createPackagePath(MODEL_PACKAGE);
        File folder = new File(packagePath);
        if (!folder.exists()) {
            System.out.println(folder.mkdirs());
        }

        File beanFile = new File(packagePath, beanName + ".java");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(beanFile)));
        bw.write("package " + MODEL_PACKAGE + ";");
        bw.newLine();
        bw.newLine();
        Set<String> set = processImportType(columns, types);
        for (String str : set) {
            bw.write(str);
            bw.newLine();
        }
        buildClassComment(bw, tableComment);
        bw.newLine();


        bw.write("public class " + beanName + "{");
        bw.newLine();
        bw.newLine();
        int size = columns.size();
        for (int i = 0; i < size; i++) {
            bw.write("\n  /**" + comments.get(i) + "**/");
            bw.newLine();
            bw.write("\n  private " + processType(types.get(i)) + " "
                    + processField(columns.get(i)) + ";");
            bw.newLine();
            bw.newLine();
        }
        bw.newLine();
        // 生成get 和 set方法
        String tempField;
        String tempFieldTwo;
        String tempType;
        for (int i = 0; i < size; i++) {
            tempType = processType(types.get(i));
            tempFieldTwo = processField(columns.get(i));
            tempField = tempFieldTwo.substring(0, 1).toUpperCase() + tempFieldTwo.substring(1);
            bw.newLine();
            bw.write("\n  public void set" + tempField + "(" + tempType + " " + tempFieldTwo + ") { ");
            bw.write("\r    this." + tempFieldTwo + " = " + tempFieldTwo + ";");
            bw.write("\n  }");
            bw.newLine();
            bw.newLine();
            bw.write("\n  public " + tempType + " get" + tempField + "() { ");
            bw.write("\r    return this." + tempFieldTwo + ";");
            bw.write("\n  }");
            bw.newLine();
        }
        bw.newLine();
        bw.write("}");
        bw.newLine();
        bw.flush();
        bw.close();
    }

    /**
     * 构建Mapper文件
     *
     * @param columns 列
     * @param types   类型
     * @author 石一歌
     * @date 2022/7/7 22:34
     */
    private void buildMapper(List<String> columns, List<String> types) throws IOException {
        File folder = new File(MAPPER_PATH);
        if (!folder.exists()) {
            System.out.println(folder.mkdirs());
        }

        File mapperFile = new File(MAPPER_PATH, mapperName + "Dao.java");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
                mapperFile), StandardCharsets.UTF_8));
        bw.write("package " + DAO_PACKAGE + ";");
        bw.newLine();
        bw.newLine();
        bw.write("import java.util.List;");
        bw.newLine();
        bw.write("import " + MODEL_PACKAGE + "." + beanName + ";");
        bw.newLine();
        bw.write("import com.bmw.first.utils.bean.CommonQueryBean;");
        bw.newLine();
        bw.newLine();
        bw.write("import org.apache.ibatis.annotations.Param;");
        bw.newLine();
        bw.write("import org.springframework.stereotype.Repository;");

        buildClassComment(bw, mapperName + "数据库操作接口类");
        bw.newLine();
        bw.newLine();
        bw.write("@Repository");
        bw.newLine();
        bw.write("public interface " + mapperName + "Dao" + "{");
        bw.newLine();
        bw.newLine();
        // ----------定义Mapper中的方法Begin----------
        buildMethodComment(bw, "查询(根据主键ID查询)");
        bw.newLine();
        bw.write("\t" + beanName + "  selectByPrimaryKey ( @Param(\""
                + processField(columns.get(0)) + "\") " + processType(types.get(0)) + " "
                + processField(columns.get(0)) + " );");
        bw.newLine();
        buildMethodComment(bw, "删除(根据主键ID删除)");
        bw.newLine();
        bw.write("\t" + "int deleteByPrimaryKey ( @Param(\"" + processField(columns.get(0))
                + "\") " + processType(types.get(0)) + " " + processField(columns.get(0)) + " );");
        bw.newLine();
        buildMethodComment(bw, "添加");
        bw.newLine();
        bw.write("\t" + "int insert( " + beanName + " record );");
        bw.newLine();
        buildMethodComment(bw, "修改 (匹配有值的字段)");
        bw.newLine();
        bw.write("\t" + "int updateByPrimaryKeySelective( " + beanName + " record );");
        bw.newLine();
        buildMethodComment(bw, "list分页查询");
        bw.newLine();
        bw.write("\t" + "List<" + beanName + "> list4Page ( " + beanName
                + " record, @Param(\"commonQueryParam\") CommonQueryBean query);");
        bw.newLine();

        buildMethodComment(bw, "count查询");
        bw.newLine();
        bw.write("\t" + "long count ( " + beanName + " record);");
        bw.newLine();

        buildMethodComment(bw, "list查询");
        bw.newLine();
        bw.write("\t" + "List<" + beanName + "> list ( " + beanName + " record);");
        bw.newLine();

        // ----------定义Mapper中的方法End----------
        bw.newLine();
        bw.write("}");
        bw.flush();
        bw.close();
    }

    /**
     * 构建实体类映射XML文件
     *
     * @param columns 列
     * @param types   类型
     * @author 石一歌
     * @date 2022/7/7 22:32
     */
    private void buildMapperXml(List<String> columns, List<String> types)
            throws IOException {
        File folder = new File(XML_PATH);
        if (!folder.exists()) {
            System.out.println(folder.mkdirs());
        }

        File mapperXmlFile = new File(XML_PATH, mapperName + ".xml");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
                mapperXmlFile)));
        bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        bw.newLine();
        bw.write("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" ");
        bw.newLine();
        bw.write("    \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">");
        bw.newLine();
        bw.write("<mapper namespace=\"" + DAO_PACKAGE + "." + mapperName + "Dao\">");
        bw.newLine();
        bw.newLine();

        buildMysql(bw, columns, types);

        bw.write("</mapper>");
        bw.flush();
        bw.close();
    }

    private void buildMysql(BufferedWriter bw, List<String> columns, List<String> types)
            throws IOException {
        bw.write("\t<resultMap id=\"" + beanName + "\" type=\"" + MODEL_PACKAGE + "." + beanName
                + "\" >");
        bw.newLine();
        for (int i = 1; i < columns.size(); i++) {
            bw.write("\t\t" + "<result column=\"" + columns.get(i) + "\" property=\""
                    + processField(columns.get(i)) + "\"/>");
            bw.newLine();
        }
        bw.write("\t</resultMap>");
        bw.newLine();
        bw.newLine();
        int size = columns.size();
        // 通用结果列
        bw.write("\t<!-- 通用查询结果列-->");
        bw.newLine();
        bw.write("\t<sql id=\"Base_Column_List\">");
        bw.newLine();
        for (int i = 0; i < size; i++) {
            bw.write("\t\t" + columns.get(i));
            if (i != size - 1) {
                bw.write(",");
                bw.newLine();
            }
        }
        bw.newLine();
        bw.write("\t</sql>");
        bw.newLine();
        bw.newLine();
        bw.write("\t<!-- 查询(根据主键ID查询) -->");
        bw.newLine();
        bw.write("\t<select id=\"selectByPrimaryKey\" resultMap=\"" + beanName
                + "\" parameterType=\"java.lang." + processType(types.get(0)) + "\">");
        bw.newLine();
        bw.write("\t\t SELECT");
        bw.newLine();
        bw.write("\t\t <include refid=\"Base_Column_List\" />");
        bw.newLine();
        bw.write("\t\t FROM " + tableName);
        bw.newLine();
        bw.write("\t\t WHERE " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}");
        bw.newLine();
        bw.write("\t</select>");
        bw.newLine();
        bw.newLine();
        bw.write("\t<!--删除:根据主键ID删除-->");
        bw.newLine();
        bw.write("\t<delete id=\"deleteByPrimaryKey\" parameterType=\"java.lang."
                + processType(types.get(0)) + "\">");
        bw.newLine();
        bw.write("\t\t DELETE FROM " + tableName);
        bw.newLine();
        bw.write("\t\t WHERE " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}");
        bw.newLine();
        bw.write("\t</delete>");
        bw.newLine();
        bw.newLine();
        bw.write("\t<!-- 添加 -->");
        bw.newLine();
        bw.write("\t<insert id=\"insert\" parameterType=\"" + MODEL_PACKAGE + "." + beanName
                + "\" >");
        bw.newLine();
        bw.write("\t\t INSERT INTO " + tableName);
        bw.newLine();
        bw.write(" \t\t(");
        bw.newLine();
        for (int i = 0; i < size; i++) {
            bw.write("\t\t\t " + columns.get(i));
            if (i != size - 1) {
                bw.write(",");
            }
            bw.newLine();
        }
        bw.write("\t\t) ");
        bw.newLine();
        bw.write("\t\t VALUES ");
        bw.newLine();
        bw.write(" \t\t(");
        bw.newLine();
        for (int i = 0; i < size; i++) {
            bw.write("\t\t\t " + "#{" + processField(columns.get(i)) + "}");
            if (i != size - 1) {
                bw.write(",");
            }
            bw.newLine();
        }
        bw.write(" \t\t) ");
        bw.newLine();
        bw.write("\t\t <selectKey keyProperty=\"" + processField(columns.get(0))
                + "\" resultType=\"" + processType(types.get(0)) + "\" order=\"AFTER\">");
        bw.newLine();
        bw.write("\t\t\t select LAST_INSERT_ID()");
        bw.newLine();
        bw.write("\t\t </selectKey>");
        bw.newLine();
        bw.write("\t</insert>");
        bw.newLine();
        bw.newLine();
        String tempField;
        bw.write("\t<!-- 修 改-->");
        bw.newLine();
        bw.write("\t<update id=\"updateByPrimaryKeySelective\" parameterType=\"" + MODEL_PACKAGE
                + "." + beanName + "\" >");
        bw.newLine();
        bw.write("\t\t UPDATE " + tableName);
        bw.newLine();
        bw.write(" \t\t <set> ");
        bw.newLine();
        for (int i = 1; i < size; i++) {
            tempField = processField(columns.get(i));
            if (processTypeIfCase(types.get(i))) {
                bw.write("\t\t\t<if test=\"" + tempField + " != null and " + tempField
                        + " != ''\">");
            } else {
                bw.write("\t\t\t<if test=\"" + tempField + " != null\">");
            }
            bw.newLine();
            bw.write("\t\t\t\t " + columns.get(i) + " = #{" + tempField + "},");
            bw.newLine();
            bw.write("\t\t\t</if>");
            bw.newLine();
        }
        bw.newLine();
        bw.write(" \t\t </set>");
        bw.newLine();
        bw.write("\t\t WHERE " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}");
        bw.newLine();
        bw.write("\t</update>");
        bw.newLine();
        bw.newLine();
        bw.write("\t<!-- list4Page 分页查询-->");
        bw.newLine();
        bw.write("\t<select id=\"list4Page\" resultMap=\"" + beanName + "\">");
        newLine(bw);
        for (int i = 0; i < size; i++) {
            tempField = processField(columns.get(i));
            if (processTypeIfCase(types.get(i))) {
                bw.write("\t\t<if test=\"record." + tempField + " != null and record." + tempField
                        + " != ''\">");
            } else {
                bw.write("\t\t<if test=\"record." + tempField + " != null\">");
            }
            bw.newLine();
            bw.write("\t\t\t and " + columns.get(i) + " = #{record." + tempField + "} ");
            bw.newLine();
            bw.write("\t\t</if>");
            bw.newLine();
        }
        bw.write("\t\t<if test=\"" + "commonQueryParam" + " != null\">");
        bw.newLine();
        bw.write("\t\t\t<if test=\"commonQueryParam.order != null \">");
        bw.newLine();
        bw.write("\t\t\t\t order by #{commonQueryParam.order}");
        bw.write("\t\t\t<if test=\"commonQueryParam.sort != null \">");
        bw.write("\t\t\t\t #{commonQueryParam.sort}");
        bw.write("\t\t\t</if>");
        bw.newLine();
        bw.write("\t\t\t</if>");
        bw.newLine();
        bw.write("\t\t\t<if test=\"commonQueryParam.start != null  and commonQueryParam.pageSize != null\">");
        bw.newLine();
        bw.write("\t\t\t\t limit #{commonQueryParam.start}, #{commonQueryParam.pageSize}");
        bw.newLine();
        bw.write("\t\t\t</if>");
        bw.newLine();
        bw.write("\t\t</if>");
        bw.newLine();
        bw.write("\t</select>");
        bw.newLine();
        bw.write("\t<!-- count 总数-->");
        bw.newLine();
        bw.write("\t<select id=\"count\" resultType=\"long\">");
        bw.newLine();
        bw.write("\t\t SELECT ");
        bw.newLine();
        bw.write("\t\t count(1) ");
        bw.newLine();
        bw.write("\t\t from " + tableName);
        bw.newLine();
        bw.write(" \t\t where 1=1  ");
        bw.newLine();
        forProcessField(bw, columns, types, size);
        bw.write("\t<!-- list 查询-->");
        bw.newLine();
        bw.write("\t<select id=\"list\" resultMap=\"" + beanName + "\">");
        newLine(bw);
        forProcessField(bw, columns, types, size);
    }

    private void forProcessField(BufferedWriter bw, List<String> columns, List<String> types, int size) throws IOException {
        String tempField;
        for (int i = 0; i < size; i++) {
            tempField = processField(columns.get(i));
            if (processTypeIfCase(types.get(i))) {
                bw.write("\t\t<if test=\"" + tempField + " != null and " + tempField + " != ''\">");
            } else {
                bw.write("\t\t<if test=\"" + tempField + " != null\">");
            }
            bw.newLine();
            bw.write("\t\t\t and " + columns.get(i) + " = #{" + tempField + "} ");
            bw.newLine();
            bw.write("\t\t</if>");
            bw.newLine();
        }
        bw.write("\t</select>");
        bw.newLine();
    }

    private void newLine(BufferedWriter bw) throws IOException {
        bw.newLine();
        bw.write("\t\t SELECT ");
        bw.newLine();
        bw.write("\t\t <include refid=\"Base_Column_List\" />");
        bw.newLine();
        bw.write("\t\t from " + tableName);
        bw.newLine();
        bw.write(" \t\t where 1=1  ");
        bw.newLine();
    }

    /**
     * 获取所有的数据库表注释
     *
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @author 石一歌
     * @date 2022/7/7 22:30
     */
    private Map<String, String> getTableComment() throws SQLException {
        Map<String, String> maps = new HashMap<>(16);
        PreparedStatement pState = conn.prepareStatement("show table status");
        ResultSet results = pState.executeQuery();
        while (results.next()) {
            String tableName = results.getString("NAME");
            String comment = results.getString("COMMENT");
            maps.put(tableName, comment);
        }
        return maps;
    }

    public void generate() throws ClassNotFoundException, SQLException, IOException {
        init();
        String prefix = "show full fields from ";
        List<String> columns;
        List<String> types;
        List<String> comments;
        PreparedStatement pState;
        List<String> tables = getTables();
        Map<String, String> tableComments = getTableComment();
        for (String table : tables) {
            columns = new ArrayList<>();
            types = new ArrayList<>();
            comments = new ArrayList<>();
            pState = conn.prepareStatement(prefix + table);
            ResultSet results = pState.executeQuery();
            while (results.next()) {
                columns.add(results.getString("FIELD").toLowerCase());
                types.add(results.getString("TYPE"));
                comments.add(results.getString("COMMENT"));
            }
            tableName = table;
            processTable(table);
            String tableComment = tableComments.get(tableName);
            buildEntityBean(columns, types, comments, tableComment);
            buildMapper(columns, types);
            buildMapperXml(columns, types);
        }
        conn.close();
    }
}
/**
 * 通用分页查询条件Bean
 * @author 石一歌
 * @date 2022-07-07 22:14
 */
public class CommonQueryBean {

    private Integer pageNum;
    private Integer pageSize;
    private Integer start;
    private String sort;
    private String order;
    private Integer page;
    private Integer rows;

    public Integer getPageNum() {
        return pageNum;
    }

    public void setPageNum(Integer pageNum) {
        this.pageNum = pageNum;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getStart() {
        return start;
    }

    public void setStart(Integer start) {
        this.start = start;
    }

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public String getOrder() {
        return order;
    }

    public void setOrder(String order) {
        this.order = order;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }

}

接口包装

@Data
public class BaseRequest<T> implements Serializable {
    private String deviceType;
    private String deviceNo;
    private String version;
    private String channelId;
    private T data;
    public BaseRequest() {
    }
}
public class BaseResponse<T> implements Serializable {
    public static final BaseResponse OK = new BaseResponse(0, "成功", "");
    private Integer code;
    private String message;
    private T data;
    public BaseResponse(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
    //成功,返回单个对象,或者返回泛型
    public static BaseResponse ok(Object o) {
        return new BaseResponse(0, "成功", o);
    }
    public static <T> BaseResponse<T> OK(T t) {
        return new BaseResponse(0, "成功", t);
    }
    //失败,返回错误信息,或者错误信息带对象
    public static BaseResponse error(Integer code, String message) {
        return new BaseResponse(code, message, null);
    }
    public static <T> BaseResponse<T> error(Integer code, String message, T data) {
        return new BaseResponse(code, message, data);
    }
}

全局异常

@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {
    /**
     * 全局异常,记录错误日志文件
     *
     * @param throwable 全局异常
     * @return com.bmw.seed.util.bean.BaseResponse<?>
     * @author 石一歌
     * @date 2022/7/13 23:58
     */
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse<?> exception(Throwable throwable) {
        log.error("系统异常", throwable);
        return BaseResponse.error(306, "服务器太忙碌了~让它休息一会吧!");
    }
}

Swagger

Knife4j

http://localhost:8080/doc.html

        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>
@Configuration
@EnableOpenApi
public class Knife4jConfig {
    /**
     * Knife4j配置
     *
     * @param environment 环境参数
     * @return Docket
     * @author 石一歌
     * @date 2022/4/11 0:39
     */
    @Bean(value = "SpringBoot-Vue-2022-Api")
    public Docket docket(Environment environment) {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(new ApiInfoBuilder()
                        .title("接口文档列表")
                        .description("接口文档")
                        .termsOfServiceUrl("http://www.springboot.vue.com")
                        .contact(new Contact("石一歌", "https://www.cnblogs.com/faetbwac/", "1456923076@qq.com"))
                        .version("1.0")
                        .license("Apache 2.0 许可")
                        .licenseUrl("许可链接").build())
                // 根据配置文件选择是否开启
                .enable(environment.acceptsProfiles(Profiles.of("dev", "test")))
                .groupName("1.0版本")
                .select()
                // 这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.nuc.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

springfox-swagger-ui

http://localhost:8080/swagger-ui.html

            <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>
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket docket(Environment environment) {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(environment.acceptsProfiles(Profiles.of("dev", "test")))
                .apiInfo(new ApiInfoBuilder().title("swagger接口文档")
                        .version("1.0")
                        .build())
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)).apis(RequestHandlerSelectors.basePackage("com"))
                .build()
                // 主要关注点----每个接口调用都填写token
                .globalOperationParameters(globalOperation());
    }

    /**
     * 为每个接口单独增加token参数
     *
     * @return java.util.List<springfox.documentation.service.Parameter>
     * @author 石一歌
     * @date 2022/7/14 11:18
     */
    private List<Parameter> globalOperation() {
        List<Parameter> pars = new ArrayList<>();
        //第一个token为传参的key,第二个token为swagger页面显示的值
        pars.add(new ParameterBuilder().name("token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build());
        return pars;
    }

}

Httpclient

@Configuration
public class HttpClientConfig {
    /**
     * 最大连接数
     */
    @Value("${http.maxTotal}")
    private Integer maxTotal;
    /**
     * 并发数
     */
    @Value("${http.defaultMaxPerRoute}")
    private Integer defaultMaxPerRoute;
    /**
     * 设置连接超时时间
     */
    @Value("${http.connectTimeout}")
    private Integer connectTimeout;
    /**
     * 设置连接请求最长时间
     */
    @Value("${http.connectionRequestTimeout}")
    private Integer connectionRequestTimeout;
    /**
     * 数据传输的最长时间
     */
    @Value("${http.socketTimeout}")
    private Integer socketTimeout;
    /**
     * 提交请求前测试连接是否可用
     */
    @Value("${http.staleConnectionCheckEnabled}")
    private boolean staleConnectionCheckEnabled;

    /**
     * 首先实例化一个连接池管理器,设置最大连接数、并发连接数
     */
    @Bean(name = "httpClientConnectionManager")
    public PoolingHttpClientConnectionManager getHttpClientConnectionManager() {
        PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
        // 最大连接数
        httpClientConnectionManager.setMaxTotal(maxTotal);
        // 并发数
        httpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
        return httpClientConnectionManager;
    }

    /**
     * 实例化连接池,设置连接池管理器。 这里需要以参数形式注入上面实例化的连接池管理器
     */
    @Bean(name = "httpClientBuilder")
    public HttpClientBuilder getHttpClientBuilder(@Qualifier("httpClientConnectionManager") PoolingHttpClientConnectionManager httpClientConnectionManager) {
        // HttpClientBuilder中的构造方法被protected修饰,所以这里不能直接使用new来实例化一个HttpClientBuilder,可以使用HttpClientBuilder提供的静态方法create()来获取HttpClientBuilder对象
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(httpClientConnectionManager);
        return httpClientBuilder;
    }

    /**
     * 注入连接池,用于获取httpClient
     */
    @Bean
    public CloseableHttpClient getCloseableHttpClient(@Qualifier("httpClientBuilder") HttpClientBuilder httpClientBuilder) {
        return httpClientBuilder.build();
    }

    /**
     * Builder是RequestConfig的一个内部类 通过RequestConfig的custom方法来获取到一个Builder对象
     * 设置builder的连接信息 这里还可以设置proxy,cookieSpec等属性。有需要的话可以在此设置
     */
    @Bean(name = "builder")
    public RequestConfig.Builder getBuilder() {
        RequestConfig.Builder builder = RequestConfig.custom();
        return builder.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(staleConnectionCheckEnabled);
    }

    /**
     * 使用builder构建一个RequestConfig对象
     */
    @Bean
    public RequestConfig getRequestConfig(@Qualifier("builder") RequestConfig.Builder builder) {
        return builder.build();
    }
}
/**
 * http对象
 *
 * @author 石一歌
 * @date 2022-07-08 15:15
 */
@Data
public class HttpResult {
    /**
     * 响应码
     */
    private Integer code;
    /**
     * 响应体
     */
    private String body;

    public HttpResult() {
        super();
    }

    public HttpResult(Integer code, String body) {
        super();
        this.code = code;
        this.body = body;
    }
}
/**
 * Http工具类
 *
 * @author 石一歌
 * @date 2022-07-08 15:12
 */
@Component
public class HttpClientUtil {
    @Resource
    private CloseableHttpClient httpClient;
    @Resource
    private RequestConfig config;

    /**
     * 不带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
     */
    public String doGet(String url) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);
        // 装载配置信息
        httpGet.setConfig(config);
        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);
        // 判断状态码是否为200
        int number200 = 200;
        if (response.getStatusLine().getStatusCode() == number200) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }

    /**
     * 带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
     */
    public String doGet(String url, Map<String, Object> map) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);
        if (map != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }
        // 调用不带参数的get请求
        return this.doGet(uriBuilder.build().toString());
    }

    /**
     * 带参数的post请求
     */
    public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        // 判断map是否为空,不为空则进行遍历,封装from表单对象
        if (map != null) {
            List<NameValuePair> list = new ArrayList<>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            // 构造from表单对象
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
            // 把表单放到post里
            httpPost.setEntity(urlEncodedFormEntity);
        }
        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8"));
    }

    /**
     * 不带参数post请求
     */
    public HttpResult doPost(String url) throws Exception {
        return this.doPost(url, null);
    }
}
http:
  maxTotal: 300
  defaultMaxPerRoute: 50
  connectTimeout: 1000
  connectionRequestTimeout: 500
  socketTimeout: 5000
  staleConnectionCheckEnabled: true

Redisclient

/**
 * redis配置
 *
 * @author 石一歌
 * @date 2022-07-11 22:18
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * template相关配置
     *
     * @param factory 工厂
     * @return org.springframework.data.redis.core.RedisTemplate<java.lang.String, java.lang.Object>
     * @author 石一歌
     * @date 2022/7/11 22:27
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);
        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(om);
        // 值采用json序列化
        template.setValueSerializer(serializer);
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 对hash类型的数据操作
     *
     * @param redisTemplate redis模板
     * @return org.springframework.data.redis.core.HashOperations<java.lang.String, java.lang.String, java.lang.Object>
     * @author 石一歌
     * @date 2022/7/11 22:26
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(
            RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * 对redis字符串类型数据操作
     *
     * @param redisTemplate redis模板
     * @return org.springframework.data.redis.core.ValueOperations<java.lang.String, java.lang.Object>
     * @author 石一歌
     * @date 2022/7/11 22:26
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(
            RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * 对链表类型的数据操作
     *
     * @param redisTemplate redis模板
     * @return org.springframework.data.redis.core.ListOperations<java.lang.String, java.lang.Object>
     * @author 石一歌
     * @date 2022/7/11 22:25
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * 对无序集合类型的数据操作
     *
     * @param redisTemplate redis模板
     * @return org.springframework.data.redis.core.SetOperations<java.lang.String, java.lang.Object>
     * @author 石一歌
     * @date 2022/7/11 22:25
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * 对有序集合类型的数据操作
     *
     * @param redisTemplate redis模板
     * @return org.springframework.data.redis.core.ZSetOperations<java.lang.String, java.lang.Object>
     * @author 石一歌
     * @date 2022/7/11 22:25
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}
/**
 * redis工具类
 *
 * @author 石一歌
 * @date 2022-07-11 22:22
 */
@Component
public class RedisUtil {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private ZSetOperations<String, Object> zSetOperations;

    public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
            }
        }
    }
    // ============================String=============================

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几(小于0)
     * @return
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }
    // ================================Map=================================

    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     * @return
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     * @return
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }
    // ============================set=============================

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) {
                expire(key, time);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    // ===============================list=================================

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     * @return
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 模糊查询获取key值
     *
     * @param pattern
     * @return
     */
    public Set keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    /**
     * 使用Redis的消息队列
     *
     * @param channel
     * @param message 消息内容
     */
    public void convertAndSend(String channel, Object message) {
        redisTemplate.convertAndSend(channel, message);
    }
    // =========BoundListOperations 用法 start============

    /**
     * 根据起始结束序号遍历Redis中的list
     *
     * @param listKey
     * @param start   起始序号
     * @param end     结束序号
     * @return
     */
    public List<Object> rangeList(String listKey, long start, long end) {
        // 绑定操作
        BoundListOperations<String, Object> boundValueOperations = redisTemplate
                .boundListOps(listKey);
        // 查询数据
        return boundValueOperations.range(start, end);
    }

    /**
     * 弹出右边的值 --- 并且移除这个值
     *
     * @param listKey
     */
    public Object rifhtPop(String listKey) {
        // 绑定操作
        BoundListOperations<String, Object> boundValueOperations = redisTemplate
                .boundListOps(listKey);
        return boundValueOperations.rightPop();
    }

    // =========BoundListOperations 用法 End============
    // =========zSetOperations 用法 start============
    public Double zincrby(String key, String member, double score) {
        return zSetOperations.incrementScore(key, member, score);
    }

    public Set<ZSetOperations.TypedTuple<Object>> zrevrangeByScoreWithScores(String key, double min, double max) {
        // 绑定操作
        return zSetOperations.reverseRangeByScoreWithScores(key, min, max);
    }
    // =========zSetOperations 用法 End============
}
spring:
  mvc:
    redis: # Redis数据库索引(默认为0)
      database: '0'
      host: 127.0.0.1 #39.98.55.177  Redis服务器地址
      port: 6379  # Redis服务器连接端口
      password: #HuAxIad0e37EE6054667bd9745d5400ecabc  Redis服务器连接密码(默认为空)
      timeout: 1000 # 连接超时时间(毫秒)
      jedis:
        pool:
          max-active: 200  # 连接池最大连接数(使用负值表示没有限制)
          max-wait: -1  # 连接池最大阻塞等待时间(使用负值表示没有限制)
          max-idle: 10 # 连接池中的最大空闲连接
          min-idle: 0  # 连接池中的最小空闲连接
posted @ 2022-08-03 22:42  Faetbwac  阅读(16)  评论(0编辑  收藏  举报