Wen Xinyiyan’s coding ability test: Can Wenxinyiyan replace programmers?

Wen Xinyiyan’s experience using code assistance capabilities. This blog was basically written with Wenxinyiyan’s help. The material is a conversation between Wenxinyiyan and I. The domestic large language model has indeed achieved great achievements. After talking to Wenxinyiyan During the conversation, I felt that the future was already here. It was indeed different from the previous automatic question and answer robots. As for whether large-scale language models such as Wen Xin Yiyan can replace programmers to complete business codes for enterprises, I have conducted multiple coding ability tests. Here is a summary:

I think Wen Xin Yi Yan is a useful tool that can be used as a programmer's right-hand assistant. However, in the key code aspects, Wen Xinyiyan cannot fully realize the requirements without loopholes. We still need to rely on the programmers' own experience and skills to complete the task. After all, there are still certain differences between machines and people. I hope Wen Xinyiyan can make more optimizations and improvements in this area in the future, let us wait and see.

Wen Xinyiyan’s self-introduction:

Q: An introduction to Wenxin Yiyan, focusing on its coding capabilities.
A: Wenxin Yiyan (ERNIE Bot) is a generative dialogue product launched by Baidu based on Wenxin large model technology. It has code generation capabilities and can understand and generate natural language text, and can provide high-quality code solutions with clear logic, complete code, and strong executability based on the questions or needs raised by users.
Wen Xinyiyan’s coding ability is mainly reflected in the following aspects:

  1. Code logic understanding and generation: Wen Xinyiyan can understand the code logic input by the user and generate complete and executable code fragments based on this logic. For example, when a user inputs a requirement for a sorting algorithm, Wen Xinyiyan can generate a code implementation of a quick sorting algorithm.
  2. Automatic code error correction: Wen Xinyiyan has an automatic error correction function, which can detect common problems such as grammatical errors and type errors in the code entered by users, and provide corresponding error prompts and repair suggestions.
  3. Code template generation: Wenxinyiyan can provide a variety of commonly used code templates based on different programming languages ​​and scenarios to facilitate users to quickly start development tasks.
  4. Code reasoning ability: Wen Xinyiyan has certain code reasoning ability and can deduce some new conclusions or solutions based on existing code logic. For example, when a user enters a code for sorting an array, Wenxinyiyan can infer statistical information such as the minimum, maximum, and average values ​​of the array.
    In short, Wen Xinyiyan's coding ability is relatively strong and can provide programmers with all-round help, greatly improving development efficiency and quality.

We took an actual application scenario as an example to discuss how to achieve data consistency between cached data (such as inventory) Redis and the database.
The conversation is as follows:

**Question:** Help me write a Java demo to achieve data consistency between redis and database for cached data (such as inventory)

**Answer:**The following is a Java demo that uses Spring Boot and Redis to achieve cache data consistency. We will use inventory as example data, store it in Redis and a database, and achieve consistency between the two.

First, we need to add Spring Boot and Redis dependencies to the pom.xml file:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Next, we create an entity class called Inventory to store inventory information:

@Entity
public class Inventory {
    
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String productId;
    private int quantity;

    // getters and setters
}

We then create a JpaRepository called InventoryRepository for interacting with the database:

public interface InventoryRepository extends JpaRepository<Inventory, Long> {
    
    
}

Next, we create an implementation class called InventoryService for interacting with Redis:

@Service
public class InventoryService {
    
    
    @Autowired
    private StringRedisTemplate redisTemplate;

    public void addToInventory(String productId, int quantity) {
    
    
        // 从Redis中获取库存数量,如果存在则累加,否则从数据库中获取库存数量并累加
        String key = "inventory:" + productId;
        String value = redisTemplate.opsForValue().get(key);
        if (value != null) {
    
    
            int existingQuantity = Integer.parseInt(value);
            quantity += existingQuantity;
        } else {
    
    
            Inventory inventory = inventoryRepository.findByProductId(productId);
            if (inventory != null) {
    
    
                quantity += inventory.getQuantity();
            } else {
    
    
                // 如果库存不存在,则从数据库中插入一条新的库存记录
                Inventory newInventory = new Inventory();
                newInventory.setProductId(productId);
                newInventory.setQuantity(quantity);
                inventoryRepository.save(newInventory);
            }
        }
        // 将更新后的库存数量存入Redis中
        redisTemplate.opsForValue().set(key, String.valueOf(quantity));
    }
}

In the above code, we use StringRedisTemplateto operate Redis and implement addToInventorymethods to accumulate the inventory quantity into Redis and the database. If the inventory quantity already exists in Redis, it is accumulated directly; otherwise, the inventory quantity is obtained from the database and accumulated. If the inventory does not exist, insert a new inventory record from the database. Finally, the updated inventory quantity is stored in Redis.

It should be noted that in order to ensure the consistency of cached data, we need to use transactions to wrap operations on Redis and the database. For specific implementation, please refer to the official documentation of Spring Boot and Redis.

The problem of redis data consistency is a classic problem of computer software. Unlike 1+1=2, there is no standard answer to this question. I hope Wen Xinyiyan can analyze the problem from various angles and provide a variety of solutions. , and the pros and cons of each option. But Wen Xinyiyan directly gave a "standard answer", but he didn't seem to understand my question. He only gave one case of redis updating data, which had nothing to do with my question, so I directly pointed out the problem and continued. Question:

Question: The code generated above only updates the inventory variables in redis, but inventory changes should also modify the data in the database at the same time, and ensure the consistency between redis and the database. Please optimize the above code

Answer: In order to ensure the consistency between Redis and the database, you can use the following methods to optimize the above code:

  1. Use transactions: Include Redis and database operations in the same transaction to ensure that they are either all executed successfully or all are rolled back, thereby maintaining data consistency.
  2. Use database triggers: Create a trigger in the database to automatically update the corresponding data in Redis when the inventory changes. In this way, every time the inventory changes, the database will automatically update the data in Redis synchronously.

The following is an optimized Java demo using Spring Boot and Redis to achieve cache data consistency:

First, we need to add Spring Boot and Redis dependencies to the pom.xml file:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Next, we create an entity class called Inventory to store inventory information:

@Entity
public class Inventory {
    
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String productId;
    private int quantity;

    // getters and setters
}

We then create a JpaRepository called InventoryRepository for interacting with the database:

public interface InventoryRepository extends JpaRepository<Inventory, Long> {
    
    
}

Next, we create an implementation class called InventoryService for interacting with Redis:

@Service
public class InventoryService {
    
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private InventoryRepository inventoryRepository;

    @Transactional // 使用事务来确保数据一致性
    public void addToInventory(String productId, int quantity) {
    
    
        // 更新Redis中的库存数量
        redisTemplate.opsForValue().increment(productId, quantity);
        // 更新数据库中的库存数量
        Inventory inventory = inventoryRepository.findByProductId(productId);
        if (inventory != null) {
    
    
            inventory.setQuantity(inventory.getQuantity() + quantity);
            inventoryRepository.save(inventory);
        } else {
    
    
            // 如果库存不存在,则从数据库中插入一条新的库存记录
            Inventory newInventory = new Inventory();
            newInventory.setProductId(productId);
            newInventory.setQuantity(quantity);
            inventoryRepository.save(newInventory);
        }
    }
}

In the above code, we use @Transactionalannotations to ensure that Redis and database operations are included in the same transaction. In addToInventorythe method, we first use redisTemplatethe opsForValue().incrementmethod to update the inventory quantity in Redis. We then update the inventory quantity in the database based on whether the inventory exists. If the inventory exists, the inventory quantity is accumulated and saved to the database; if the inventory does not exist, a new inventory record is inserted. Finally, inventoryRepository.save()the method automatically commits the transaction to ensure data consistency between Redis and the database.

The above code did not solve the problem at all, so I continued to ask:

Question: As I bluntly say, the above addToInventory method does not guarantee the consistency of database and redis data. If inventoryRepository.save() fails to execute, the database transaction will be rolled back, but the redis transaction will not be rolled back, and the data will not be consistent.

Answer: You are right, addToInventorythe method in the above code does not fully guarantee the consistency of the database and Redis data. If inventoryRepository.save()the execution fails, the database transaction will be rolled back, but the Redis transaction will not be rolled back, which may lead to data inconsistency.

To solve this problem, we can use distributed transactions to ensure the consistency of database and Redis data. Specifically, we can use a transaction manager to coordinate transactions between the database and Redis to ensure that they either all succeed or are all rolled back.

In Spring Boot, @Transactionaldistributed transactions can be implemented using annotations and transaction managers. The following is an optimized Java demo using Spring Boot to achieve database and Redis data consistency:

First, we need to add Spring Boot and Redis dependencies to the pom.xml file:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Next, we create an entity class called Inventory to store inventory information:

@Entity
public class Inventory {
    
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String productId;
    private int quantity;

    // getters and setters
}

We then create a JpaRepository called InventoryRepository for interacting with the database:

public interface InventoryRepository extends JpaRepository<Inventory, Long> {
    
    
}

Next, we create an implementation class called InventoryService for interacting with Redis:

@Service
public class InventoryService {
    
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private InventoryRepository inventoryRepository;
    @Autowired
    private PlatformTransactionManager transactionManager; // 事务管理器

    @Transactional // 使用事务来确保数据一致性
    public void addToInventory(String productId, int quantity) {
    
    
        // 更新Redis中的库存数量
        redisTemplate.opsForValue().increment(productId, quantity);
        // 更新数据库中的库存数量
        Inventory inventory = inventoryRepository.findByProductId(productId);
        if (inventory != null) {
    
    
            inventory.setQuantity(inventory.getQuantity() + quantity);
            inventoryRepository.saveAndFlush(inventory); // 使用saveAndFlush方法确保数据立即写入数据库
        } else {
    
    
            // 如果库存不存在,则从数据库中插入一条新的库存记录
            Inventory newInventory = new Inventory();
            newInventory.setProductId(productId);
            newInventory.setQuantity(quantity);
            inventoryRepository.saveAndFlush(newInventory); // 使用saveAndFlush方法确保数据立即写入数据库
        }
        // 提交事务,如果发生异常则回滚事务,确保数据一致性
        try {
    
    
            transactionManager.commit(transactionStatus()); // 手动提交事务,需要注意要在try块中执行此操作,以确保如果发生异常可以回滚事务
        } catch (Exception e) {
    
    
            transactionManager.rollback(transactionStatus()); // 如果发生异常则回滚事务,确保数据一致性
            throw e; // 重新抛出异常,以便调用方可以处理异常情况
        }
    }
}

In the above code, we added a transactionManagerfield, which is an PlatformTransactionManagerobject of type that is used to coordinate transactions between the database and Redis. In addToInventorythe method, we first use redisTemplatethe opsForValue().incrementmethod to update the inventory quantity in Redis. We then update the inventory quantity in the database based on whether the inventory exists. After updating the database, we use try-catchblocks to manually commit and rollback the transaction. If an exception occurs, we roll back the transaction to ensure data consistency. If no exception occurs, we commit the transaction. In this way, we can ensure data consistency between the database and Redis.

I corrected the problem twice in a row, but Wen Xinyiyan still didn't get it right. Wen Xinyiyan's knowledge reserve is no problem, the code itself can be run, and the encapsulation of methods and coding style are remarkable, but Didn't solve the problem.

During the conversation with Wen Xinyiyan, I found that it can generate some classic code cases that can solve some common problems. However, when faced with some complex requirements, I found that Wen Xinyiyan's coding capabilities had some limitations.

Although the code generated by Wen Xinyiyan is close to the requirements, there are still some loopholes. For example, in our case, when the database transaction is rolled back, the Redis modifications are not rolled back, which leads to data consistency issues.

I pointed out this problem to Wen Xinyiyan and hoped that it could be optimized. However, when I conducted the second test, I found that Wen Xinyiyan's code still had problems. Although optimization has been carried out to a certain extent, the problem is still not solved.

Although Wenxinyiyan is excellent in some aspects, it does not fully understand the requirements, which leads to some problems in the generated code. This may be because Wen Xinyiyan’s knowledge base mainly comes from past cases, and he is unable to understand and solve new problems like human programmers.

To sum up, Wen Xin Yi Yan has certain advantages. It can provide programmers with certain help, such as querying knowledge and solving common problems. However, it cannot completely replace programmers themselves. Because the computer world is full of constant discovery and problem solving, and the quality of cases on the web varies. Therefore, programmers still need to carefully review the generated code to ensure the quality and reliability of the code.

Guess you like

Origin blog.csdn.net/weixin_41674401/article/details/132920468