Redis practice - data structure List practice 1: orderly storage of commodity information

Overview: the related content of this series of blog articles comes from the actual combat course recorded by debug in person: Introduction to Redis technology and application scenario practice (SpringBoot2.x + red packet system design and practice) , interested partners can click to learn by themselves (after all, mastering technology in the form of video will be faster!) , column: Introduction and practice of Redis Technology

Abstract: the management backend of e-commerce platform generally has two roles for users to use, one is the system administrator, the other is the seller / merchant of the platform. For merchants, managing their own commodities is a common thing in daily work. In this paper, we will use "orderly storage and display of various commodity lists uploaded by merchants in e-commerce platform", here The key word of Redis is "orderly storage and display". We will use the data structure ~ List list of Redis, the caching middleware, to carry out the actual implementation!

Content: for Redis data structure - List list, in the actual project development practice, it is also one of the more common and widely used data structures! The underlying data storage structure is very similar to the List of Java se collection system, that is, the data is ordered and arranged at the bottom. When the data in the List is obtained, it will be found that the data in the List is indeed arranged in order. A simple List storage and acquisition flow chart is drawn for you, as shown below:

From the figure, we can see that when we add data to the Redis List, it has the "first in, first out" feature, which is called "FIFO" (a bit of Queue feature!) And the data is compact, one by one! That is to say, when we add data to the List of Redis, we can add it to the List of Redis in the way of "LPush is to add data from the left", and then use the way of "LPop is to eject data from the left" or "RPop is to eject data from the right" to obtain the orderly stored List data!

Knowing the data storage and reading process of List, we almost know the code implementation in the actual project development. Next, we use "e-commerce platform - how to store the List of goods in an orderly manner to the List of Redis cache when the merchants add / remove the goods from the shelves, and each time we get the current List of goods of the merchants, we can read it directly from the cache, so as to reduce the pressure that each merchant needs to go to the database DB frequently after each login!"

(1) First, of course, a "product information table" is needed. Its complete DDL (data definition language) is as follows:

CREATE TABLE `product` (
  `name` varchar(255) CHARACTER SET utf8mb4 NOT NULL COMMENT 'Trade name',
  `user_id` int(11) NOT NULL COMMENT 'Affiliated merchant id',
  `scan_total` int(255) DEFAULT NULL COMMENT 'Browse volume',
  `is_active` tinyint(255) DEFAULT '1' COMMENT 'Is it effective?',  PRIMARY KEY (`id`),
  KEY `indx_scan_total` (`scan_total`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Merchant goods list';

(2) Then, of course, we need to develop a Controller. In this Controller, we need to set up two request methods, one is to use "add goods" (enter DB and insert Redis) for merchants, the other is to obtain the "goods list" that has been added by current merchants. The complete source code is as follows:

 * List list actual combat - store merchant commodity list
 * @Author:debug (SteadyJack)
 * @Link: weixin-> debug0868 qq-> 1948831260
 * @Date: 2019/10/30 20:58
public class ListController extends AbstractController{
    private ListService listService;
    //Add to
    @RequestMapping(value = "put",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BaseResponse put(@RequestBody Product product,BindingResult result){
        BaseResponse response=new BaseResponse(StatusCode.Success);
        try {
  "--Merchant product information:{}",product);
        }catch (Exception e){
            log.error("--List actual combat-Merchant goods-Add to-Exception occurred:",e.fillInStackTrace());
            response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        return response;
    //Get list details
    @RequestMapping(value = "get",method = RequestMethod.GET)
    public BaseResponse get(@RequestParam("userId") final Integer userId){
        BaseResponse response=new BaseResponse(StatusCode.Success);
        try {
        }catch (Exception e){
            log.error("--List actual combat-Merchant goods-Get list-Exception occurred:",e.fillInStackTrace());
            response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        return response;

(3) Next, we need to develop the Service corresponding to the Controller, whose responsibility is to process the real business logic. When adding a product, it is responsible for adding the product information to the DB database and adding it to the Redis cache. When obtaining a product, it is natural to retrieve the List data from the Redis cache. The complete source code is as follows:

 * List list service
 * @Author:debug (SteadyJack)
 * @Link: weixin-> debug0868 qq-> 1948831260
 * @Date: 2019/10/30 9:48
public class ListService {
    public static final Logger log= LoggerFactory.getLogger(ListService.class);
    private ProductMapper productMapper;
    private RedisTemplate redisTemplate;
    //Add merchandise
    @Transactional(rollbackFor = Exception.class)
    public Integer addProduct(Product product) throws Exception{
        if (product!=null){
                //Insert the product into the database DB
            Integer id=product.getId();
            if (id>0){
                       //Insert the product into Redis
            return id;
        return -1;
    //TODO: plug information into the cache - can be extracted to ListRedisService
    private void pushRedisService(final Product product) throws Exception{
        ListOperations<String,Product> listOperations=redisTemplate.opsForList();
    //Get the list of products published in history
    public List<Product> getHistoryProducts(final Integer userId) throws Exception{
        List<Product> list= Lists.newLinkedList();
        ListOperations<String,Product> listOperations=redisTemplate.opsForList();
        final String key=Constant.RedisListPrefix+userId;
        //TODO: reverse order - > userid = 10010 - > rabbitmq introduction and practice, Redis introduction and practice, spring boot project practice
        list=listOperations.range(key,0,listOperations.size(key));"--Reverse order:{}",list);
        //TODO: sequence - > userid = 10010 - > spring boot project practice, Redis introduction and practice, Rabbitmq introduction and Practice
        //"-- Order: {}", list);
        //TODO: how to pop it out and remove it
        //Product entity=listOperations.rightPop(key);
        //while (entity!=null){
        return list;

(4) At this point, our code practice is over. Finally, let's enter the test phase based on Postman. Let's add two products to merchant 10010, as shown below:

After completion, you can also go to Mysql database to view the list of products that have just been added, as shown in the following figure:

Finally, we launched "get the list of goods that have been added by the current merchant - orderly display" in Postman (the "order" and "reverse order" can be achieved by modifying the code), as follows:

Well, we've introduced this article here. I suggest that you should follow the sample code provided in this article, and only after it can you know how to use it, otherwise you will become a "talker"! Those who are interested in Redis related technology stack and practical application scenario can learn from the course recorded by 51cto college debug in person: Introduction to Redis technology and application scenario practice (SpringBoot2.x + red packet system design and practice)


1. The relevant source code involved in this article can be check ed at this address for viewing and learning:

2. At present, debug has organized and recorded the content involved in this article into a video tutorial. Interested partners can go to watch and learn:

Keywords: Java Redis Database RabbitMQ Spring

Added by The.Pr0fess0r on Fri, 07 Feb 2020 13:42:45 +0200