AI (1): First experience (develop an application from scratch with the help of ChatGPT)

  • demand analysis
  • database modeling
  • interface documentation
  • full backend service
  • unit test

Template 1: Use ChatGPT to develop from scratch to support tens of thousands of concurrent seckill systems

1. ME: ask questions

假设你是Java架构师,请用Java语言开发一个秒杀下单接口,要求如下:
2. 将数据库里的商品库存预先加载到redis里面存储
3. 下单操作时先检查rediss里的商品库存是否足够扣减
4. 如果redis里有足够库存就先扣减库存然后再生产订单

2. ChatGPT: Reply

As a Java architect, I can provide a simple way to implement the seckill order interface to meet your requirements:
First, you need to introduce the Java client library of Redis and MySQL to connect and operate Redis and MySQL in Java programs database.
Then, we can write the implementation of the seckill order interface as follows:

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class SecKillOrderService {
    
    
    // Redis 连接相关配置
    private static final String REDIS_HOST = "localhost";
    private static final int REDIS_PORT = 6379;
    private static final String REDIS_PASSWORD = null; // 如果 Redis 无密码可以不设置
    private static final int REDIS_TIMEOUT = 10000;
    // Redis 商品库存 key 前缀
    private static final String STOCK_PREFIX = "stock_";
    // MySQL 连接相关配置
    private static final String MYSQL_URL = "jdbc:mysql://localhost:3306/dbname?useSSL=false";
    private static final String MYSQL_USER = "username";
    private static final String MYSQL_PASSWORD = "password";

    /**
     * 秒杀下单接口
     *
     * @param productId 商品 ID
     * @param userId    用户 ID
     * @return 下单成功返回订单 ID,库存不足返回 null
     */
    public String secKillOrder(long productId, long userId) {
    
    
        // 初始化 Redis 连接
        Jedis jedis = new Jedis(REDIS_HOST, REDIS_PORT, REDIS_TIMEOUT);
        if (REDIS_PASSWORD != null) {
    
    
            jedis.auth(REDIS_PASSWORD);
        }

        // 构造商品库存 key
        String stockKey = STOCK_PREFIX + productId;

        // Redis WATCH 操作,用于乐观锁控制并发操作
        jedis.watch(stockKey);
        int stock = Integer.parseInt(jedis.get(stockKey));
        if (stock <= 0) {
    
    
            // 库存不足
            jedis.unwatch();
            return null;
        }

        // Redis MULTI/EXEC 操作,用于原子地扣减库存和创建订单
        Transaction tx = jedis.multi();
        tx.decr(stockKey);
        // 模拟订单生成,插入订单到 MySQL 数据库
        String orderId = createOrder(productId, userId);
        tx.exec();

        return orderId;
    }

    /**
     * 创建订单,插入订单到 MySQL 数据库
     *
     * @param productId 商品 ID
     * @param userId    用户 ID
     * @return 订单 ID
     */
    private String createOrder(long productId, long userId) {
    
    
        String orderId = null;
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
    
    
            // 初始化 MySQL 连接
            conn = DriverManager.getConnection(MYSQL_URL, MYSQL_USER, MYSQL_PASSWORD);

            // 开始 MySQL 事务
            conn.setAutoCommit(false);

            // 构造 SQL 插入语句,插入订单
            String sql = "INSERT INTO orders (product_id, user_id) VALUES (?, ?)";
            stmt = conn.prepareStatement(sql);
            stmt.setLong(1, productId);
            stmt.setLong(2, userId);
            stmt.executeUpdate();

            // 获取插入的订单 ID
            sql = "SELECT LAST_INSERT_ID()";


3. ME: ask questions

继续

4. ChatGPT: Reply

        stmt = conn.prepareStatement(sql);
        orderId = stmt.executeQuery().getString(1);

        // 提交 MySQL 事务
        conn.commit();
    } catch (SQLException e) {
    
    
        // 如果 MySQL 出现异常,则回滚事务
        if (conn != null) {
    
    
            try {
    
    
                conn.rollback();
            } catch (SQLException ex) {
    
    
                ex.printStackTrace();
            }
        }
        e.printStackTrace();
    } finally {
    
    
        // 关闭 MySQL 连接和语句对象
        if (stmt != null) {
    
    
            try {
    
    
                stmt.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
        if (conn != null) {
    
    
            try {
    
    
                conn.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
    }

    return orderId;
}
}

In the above code, we use Redis to store commodity inventory, and check whether the commodity inventory in Redis is sufficient before placing an order. If there is sufficient inventory in Redis, we use Redis's WATCH operation to perform optimistic lock control concurrent operations, and then use Redis The MULTI/EXEC operation performs an atomic deduction of inventory and creation of an order. At the same time, we use JDBC to connect to the MySQL database in the createOrder method, insert the order and return the order ID. It should be noted that the above code is just a simple example, and the actual seckill scenario may require more optimization and expansion, such as using Redis cluster for high availability and distributed lock control.

5. ME: ask questions

I hope to change the order generation method xxxxx to send the order to MQ, and then asynchronously consume the generated order to the data

6. ME: ask questions

Now I need to ensure the high availability of the order interface. What should I do if the redis service hangs up during the order process?

7. ME: ask questions

I hope you handle it like this. If the redis service hangs up during the order placing process, we can cache this request in a local cache or file, and then retry to access Redis at regular intervals. If Redis responds, we continue to place the order

8. ME: ask questions

continue

9. ME: ask questions

Continue to optimize the first point

10. ME: ask questions

Please continue to generate the code for placing an order and asynchronously consuming MQ to generate an order

。。。。。

Template 2: Develop a salary payment application from scratch with ChatGPT

requirements document

Salary Payment System Basic Specifications

Below are some notes we made while discussing the system with our customers.

The system contains a database of all employee information in the company, as well as other data related to the employee, such as: working time card data, etc. The system can be used to pay salaries for each employee. And the system must pay employees the correct amount of salary on time according to the specified method. At the same time, various due deductions should be deducted from the salary finally paid to the employees.

Some employees are hourly workers. In the database records for these employees, there is a field used to record their hourly salary. They are required to submit a working time card every day, which records their working dates and working hours. If they work more than 8 hours a day, they will be paid 1.5 times their normal hourly rate for the hours beyond 8 hours. These employees are paid every Friday.

Some employees are paid a fixed monthly salary. These employees are paid on the last day of each month. In the database records of these employees, there is a field used to record their monthly salary.

There are also some employees who are engaged in sales work, so they will be paid commissions based on their sales. They need to submit a sales voucher, which records the time and amount of the sale. In their database record, there is a field to record their commission rate. Commissions are paid for them every Friday of the fortnight.

Employees are free to choose how their salaries are paid. They can choose to have their paychecks mailed to their designated addresses; they can temporarily keep their paychecks with cashiers and withdraw them at any time; they can also choose to have their salaries deposited directly into their designated bank accounts.

Some employees are union members of the company. There is a field in their database record that records their weekly dues due, and their dues are deducted from their salary. In addition, the union may also assess individual union member service charges from time to time. These service charges are submitted weekly by the union and must be deducted from the respective employee's next paycheck.

set background

1. ME: ask questions

If you are a Java architect and I am a newcomer, I hope you can help me develop a program. Next, I will give you a requirement document. You should familiarize yourself with it first. I will need your help later. To do some things, let me introduce my development environment. My computer operating system is Mac, and I have installed MySQL database, JDK and IDEA. I'm ready for R&D, are you ready?

2. ChatGPT: Reply

Great, I'm ready to assist you in developing this program. Please send me the requirements document, I will read and understand the requirements in detail, and then we can discuss the best way to implement this program together. At the same time, I will also ensure that your understanding and ability of Java programming can be improved, and during the development process, I will provide you with relevant technical guidance and suggestions to help you successfully complete this project.

3. ME: ask questions

Salary Payment System Basic Specification
The following are some notes we made while discussing the system with the client.

  • The system contains a database of all employee information in the company, as well as other data related to the employee, such as: working time card data, etc. The system can be used to pay salaries for each employee. And the system must pay employees the correct amount of salary on time according to the specified method. At the same time, various due deductions should be deducted from the salary finally paid to the employees.
  • Some employees are hourly workers. In the database records for these employees, there is a field used to record their hourly salary. They are required to submit a working time card every day, which records their working dates and working hours. If they work more than 8 hours a day, they will be paid 1.5 times their normal hourly rate for the hours beyond 8 hours. These employees are paid every Friday.
  • Some employees are paid a fixed monthly salary. These employees are paid on the last day of each month. In the database records of these employees, there is a field used to record their monthly salary.
  • There are also some employees who are engaged in sales work, so they will be paid commissions based on their sales. They need to submit a sales voucher, which records the time and amount of the sale. In their database record, there is a field to record their commission rate. Commissions are paid for them every Friday of the fortnight.
  • Employees are free to choose how their salaries are paid. They can choose to have their paychecks mailed to their designated addresses; they can temporarily keep their paychecks with cashiers and withdraw them at any time; they can also choose to have their salaries deposited directly into their designated bank accounts.
  • Some employees are union members of the company. There is a field in their database record that records their weekly dues due, and their dues are deducted from their salary. In addition, the union may also assess individual union member service charges from time to time. These service charges are submitted weekly by the union and must be deducted from the respective employee's next paycheck.

4. ChatGPT: Reply

Thank you very much for the requirements document, here are some of my initial thoughts and suggestions for the system:

  1. Database design
    First, we need to design a database for the system, which should contain basic information of employees, working time card data, sales vouchers, salary payment records and other information. We can use MySQL database for design. Consider designing the following tables:
  • Employee information form: Contains basic information of employees, such as employee number, name, address, payment method, union membership, etc.
  • Working time card form: record the working time card submitted by employees every day, including employee number, date, working hours and other information.
  • Sales Voucher Form: Record sales vouchers submitted by sales employees, including employee number, date, sales amount and other information.
  • Salary payment record form: record the relevant information of each salary payment, including employee number, payment date, payment amount and other information.
  1. Salary calculation
    Next, we need to write Java code to calculate the salary of each employee and record it in the salary payment record form. According to the different payment methods and salary calculation methods described in the requirements document, we can consider using the following algorithms:
  • For employees with fixed monthly salary, it can be calculated directly based on their monthly salary.
  • For part-time workers, their salary needs to be calculated according to their submitted working time cards. If the working time exceeds 8 hours, the overtime pay shall be calculated at 1.5 times the normal hourly wage.
  • For sales staff, it is necessary to calculate their commission based on the sales voucher they submit, and calculate the commission amount based on their commission rate.
    After calculating the salary of each employee, we need to consider various due deductions, such as taxes, insurance premiums, union dues, etc., and record the salary amount after deductions in the salary payment record form.
  1. Salary payment method
    According to the salary payment method described in the requirements document, we can consider using the following algorithm:
  • For employees who choose check mailing or check custody, paychecks can be sent or kept on-site, and the check number and mailing or custody status can be recorded on the salary payment record form.
  • For employees who choose to deposit their salary into a bank account, Java code can be used to automate the bank transfer function, and the transfer status and transfer date can be recorded in the salary payment record form.
  1. Other functions
    Finally, we also need to consider the realization of some other functions, such as employee information management, trade union dues calculation, service fee deduction, etc. For employee information management, we can implement the functions of adding, modifying, and deleting employee information; for union dues calculation, we can calculate the sales employee's commission based on the sales employee's commission. The sales employee's commission should be calculated based on their sales
    . In the employee database, there is a field that records their commission rate. Every Friday of the fortnight, the system calculates their commission and pays them the corresponding commission amount. Sales employees need to submit sales vouchers, which record the sales time and amount, and these data need to be stored in the database.
  • Salary payment method
    Employees are free to choose the salary payment method. They can choose to have their paycheck mailed to the address they designate, or they can temporarily keep the paycheck with the cashier and draw it at any time. Additionally, employees have the option to have their paychecks deposited directly into their designated bank account. In order to implement these functions, the system needs to integrate with the APIs of banks and mailing service providers.

  • Membership fees and service fees of union members
    Union members need to pay certain membership fees every week, and these data need to be stored in the employee database. In addition, the union may from time to time assess individual union member service charges. These service charges are filed weekly by the union and must be deducted from the respective employee's next paycheck. The system needs to take these deductions into account when calculating payroll.

The above is the description of the basic specifications of the salary payment system, and then we can start to discuss the specific development and implementation plan.

database modeling

  1. ME asks:我希望你按照业务数据库建模规范和最佳实践给我写一份数据库建模表格文档,包含表名、列名、数据类型、约束条件、描述、枚举值(用数字代替),ID不是自增,使用雪花ID算法生成,标准字段:create_time、update_time、deleted
  2. ChatGPT: Reply
  3. ME asks:你刚因为回复长度限制问题中断了,我需要你继续回答
  4. ChatGPT: Reply
  5. ME question: We have completed the first step. I have installed MySQL8 on my computer. When designing the table structure, it is necessary to consider query performance, data size and growth trend to ensure that the system can withstand future data. Access load, and related field comment comments, table comment comments, and those that need to be indexed also need to be added. Then create table statements and index statements to speed up my
  6. ChatGPT: Reply
  7. ME question: 你刚因为回复长度限制问题中断了,我需要你继续从union_membership继续返回我建表语句
  8. ChatGPT: Reply
  9. ME question: 我需要员工表、工作时间卡表、销售凭证表、工会会员表。每张表5条左右的测试数据,覆盖了每个字段的情况,特殊字段符合中文风格要求。每条SQL语句都可以直接执行,以插入测试数据。
    由于多张表容易发生请求中断情况需要拆分,一张表一张表的创建
    I need an employee table. There are about 5 pieces of test data in the table, covering the situation of each field, and the special fields meet the requirements of the Chinese style. Each SQL statement can be executed directly to insert test data.
  10. ChatGPT: Reply
  11. ME asks:你刚因为回复长度限制问题中断了,我需要你继续回答
  12. COPY SQL statement to Mysql client to create table verification

interface documentation

  1. ME asks:按照前面生成的表结构来分析,如果需要你设计一份标准的基于RESTFul接口文档,每一个接口都需要进行分析和论证必要性和设计合理性。预计你会出多少个接口?

  2. ChatGPT: Reply

  3. ME asks:我需要员工接口的需求文档,你写完发我

  4. ChatGPT: Reply

  5. ME asks:要求:返回OpenAPI规范JSON格式,描述信息需要中文,有些情况需要分页,考虑数据边界值。接口:添加员工

  6. ChatGPT: Reply
    导入 https://app.apifox.com/project or postman

Complete the backend service

environment dependent

  1. ME asks:接下来我们就进入开发环节,我希望的技术栈是Java17+SpringBoot+MyBatisPlus+Lombok的方式进行开发,你可以一步一步教我如何搭建一个项目吗?
  2. ChatGPT: Reply
  3. ME asks:我需要lombok的pom依赖代码
  4. ChatGPT: Reply
  5. ME asks:我需要mysql8驱动的pom依赖代码
  6. ChatGPT: Reply
    Version update and Mysql database configuration still need to be modified by yourself

Entity class

  1. ME asks:基于前面你生成的4张数据库表结构,接下来我们建实体类,我要求:import语句、lombok、字段注解、类注释都需要
  2. ChatGPT: Reply
  3. ME asks:你刚因为回复长度限制问题中断了,我需要你继续回答
  4. ChatGPT: Reply
    COPY import to IDEA

Mapper

  1. ME asks:基于前面你生成的4个实体类,接下来我们建Mapper层接口,要求继承MyBatisPlus的BaseMapper类,但是不需要写任何接口
  2. ChatGPT: Reply
  3. ME asks:你给的Mapper层代码没有注入Spring
  4. ChatGPT: Reply
  5. ME asks:在Spring中注入Mapper层代码,有全局的方案吗?
  6. ChatGPT: Reply

Service

  1. ME asks:基于前面的需求文档,接下来我们开始进行核心业务功能设计,要求:利用面向对象的设计原则和设计模式,确保业务功能的实现即健康又易于维护,先不用告诉我代码实现。
  2. ChatGPT: Reply
  3. ME asks:按照你设计的业务功能。我现在需要EmployeeService的接口类和实现类,要求:结合Mybatis-Plus实现, 核心业务必须加上适当的注释
  4. ChatGPT: Reply
  5. ME asks:少了一个查询员工列表(支持分页)的接口方法
  6. ChatGPT: Reply
  7. ME asks:按照你设计的业务功能。我现在需要PaymentService的接口类和实现类,要求:结合Mybatis-Plus实现, 核心业务必须加上适当的注释,需要实现计算员工薪水(支持钟点工、月薪员工、销售员)、需要实现支付员工薪水(支持邮寄支票、暂停支票、银行账号支付)
  8. ChatGPT: Reply
  9. ME asks:在PaymentServiceImpl 当中caculateSalary的方法,我没有所属的三个子类,我也并不想创建,我想直接在里面计算
  10. ChatGPT: Reply
  11. ME asks:在PaymentServiceImpl实现类中getWorkedHours、getTotalSales找不到报错,我需要你给我实现出来
  12. ChatGPT: Reply
  13. ME asks:getTotalWorkedHours要进行修改,钟点工是每周支付一次最近一周的薪水而不是全部薪水,而销售类员工则是按照每月最后一天支付一次当月的销售额的提成。所以SQL需要进行调整
  14. ChatGPT: Reply

timed task

  1. ME asks:结合前面的业务需求和已完成的代码,我需要结合SpringBoot创建一个定时任务执行,要求:核心业务代码需要添加必要的注解,每天运行一次、每周五支付钟点工薪水、每月最后一天支付月薪员工薪水、每月最后一天支付销售员佣金
  2. ChatGPT: Reply
  3. ME asks:结合前面的业务需求和已完成的代码,我需要结合SpringBoot创建一个定时任务执行,要求:核心业务代码需要添加必要的注解,每天运行一次、每周五支付钟点工薪水、每月最后一天支付月薪员工薪水、每月最后一天支付销售员佣金,需要结合PaymentServiceImpl中calculateSalary和paySalary方法实现
  4. ChatGPT: Reply
  5. ME asks:在paymentService当中getEmployees()并没有,他应该在EmployeeService当中, 所以需要你修改一下
  6. ChatGPT: Reply
  7. ME asks:在EmployeeService当中getEmployees()方法不存在,我需要你实现出来
  8. ChatGPT: Reply

run up

  1. ME asks:当我启动SpringBoot服务时出现一个错误:xxxxxxxxx
  2. ChatGPT: Reply

unit test

  1. ME asks:基于前面实现的EmployeeService,接下来需要帮我们为所有方法进行单元测试用例的编写,要求:核心代码需要加上适当的中文注释,结合spring-boot-starter-test实现。我需要EmployeeService类中所有的方法写出来可测试的单例,并不是Demo
  2. ChatGPT: Reply
  3. ME asks:你这边缺少了一个单例测试方法listEmployees(Page<Employee> page)。我需要你补充回答
  4. ChatGPT: Reply
  5. ME asks:基于前面实现的PaymentService,接下来需要帮我们为所有方法进行单元测试用例的编写,要求:核心代码需要加上适当的中文注释,结合spring-boot-starter-test实现。我需要PaymentService类中所有的方法写出来可测试的单例,并不是Demo
  6. ChatGPT: Reply
  7. ME asks:基于前面实现的ScheduledTasks,接下来需要帮我们为所有方法进行单元测试用例的编写,要求:核心代码需要加上适当的中文注释,结合spring-boot-starter-test实现。我需要ScheduledTasks类中所有的方法写出来可测试的单例,并不是Demo
  8. ChatGPT: Reply

Dialogue flow attachment

Use ChatGPT to develop a Java flash order interface from scratch-ChatGPT.html

Develop a salary application software from scratch with the help of ChatGPT.mhtml

Guess you like

Origin blog.csdn.net/menxu_work/article/details/130385745