Redis Actual - Data Structure Set Actual Get Randomized Unique Test Title

Overview: This series of blogs covers relevant content from a hands-on course recorded by debug: Getting Started with Cache Middleware Redis Technology and Application Scenario Actual Warfare (SpringBoot2.x +Redback System Design and Warfare) , interested little buddies can click to learn on their own (after all, it's faster to master technology in the form of video!)Technical column of the article: Introduction and Practice of Cache Middleware Redis Technology

Summary: Redis, the cache middleware, has many rich, important and interesting data structures. Collection Set is one of the best. Its core feature is almost the same as Set in JavaSE collection system, which is "out of order" and "unique". When we reach for an element to a collection Set, its underlying layer randomly sends us one!In this article, we will continue to introduce and practice another typical business scenario, which is to get a random, disordered and unique list of test questions from the Examination System.

Contents: "Examination" should not be unfamiliar to many small partners, such as elementary school entrance examination, high school entrance examination, various examinations during university, many people now sign up for the "subject one" examination of a school bus, and the examinations involved in various training certificates, etc., more or less believe that everyone has experienced it!

The core of a test paper is the "topic". How to reduce the cheating rate during the exam is the most difficult problem for both the supervisor and the question-maker. Somewhere, a "talented person" came up with a very effective method, which is "try to make each examinee get the same question" (of course, the total number of questions is the same).)"

Now most of the "online examination systems" also take this way, that is, after the successful login of the "examination system", the test questions displayed in front of each examinee are almost different or the same, but the order of the questions of different examinees is completely different, that is, there are differences!Sometimes when I think about it, I have to say it's a good way to prevent cheating on the spot (True TN is a genius!),

Next, we will implement this typical business scenario in the Online Examination System based on the Set set of cached middleware Redis, which is to get a random, unique and disordered list of test questions with the core business processes shown in the following figure:

From this business process diagram, there are two main things we will do:

A. After the project starts, pull out the list of all test questions from the database DB and insert it into the cached Set collection

B. Develop a request method to retrieve random, disordered and unique N-question from the cache and return it to the candidates who are currently successfully logged in to the test system!

(1) Good work is also a must-have tool. First, we need to set up a database table "Test Title Table" to store the administrator's new title information. Its DDL is as follows:

CREATE TABLE `problem` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(150) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT 'Question Title',
  `choice_a` varchar(100) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT 'option A',
  `choice_b` varchar(100) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT 'option B',
  `is_active` tinyint(4) DEFAULT '1' COMMENT 'Is it valid(1=yes;0=no)',
  `order_by` tinyint(4) DEFAULT '0' COMMENT 'sort',
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx_title` (`title`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Test Title Table';

Entity entity classes, Mapper operation interfaces, and Mapper.xml for manipulating dynamic SQL can be generated using Mybatis reverse engineering or code generators for this database table.In addition, we have added a series of new titles (which are considered test cases) to the database table, as shown in the following figure:

(2) Next, we develop a ProblemService service class that implements "After the project starts, go to the database DB to pull the list of test questions and insert it into the cache collection Set"!It also implements the "Get Random, Randomized and Unique N-Title List from Cache Collection Set" in ProblemService, whose complete source code is as follows:

/**Test Title Service
 * @Author:debug (SteadyJack)
 * @Link: weixin-> debug0868 qq-> 1948831260
**/
@Service
public class ProblemService {
    private static final Logger log= LoggerFactory.getLogger(ProblemService.class);

    @Autowired
    private ProblemMapper problemMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    //TODO: Project startup pulls out the question library from the database and inserts it into the cache Set collection
    @PostConstruct
    public void init(){
        initDBToCache();
    }

    //TODO: Pull out the list of all titles in the database and insert them into the cache Set collection
    private void initDBToCache(){
        try {
            
 
 //redisTemplate.delete(Arrays.asList(Constant.RedisSetProblemKey,Constant.RedisSetProblemsKey));
            SetOperations<String,Problem> setOperations=redisTemplate.opsForSet();
            Set<Problem> set=problemMapper.getAll();
            if (set!=null && !set.isEmpty()){
                set.forEach(problem -> setOperations.add(Constant.RedisSetProblemKey,problem));
                set.forEach(problem -> setOperations.add(Constant.RedisSetProblemsKey,problem));
            }
        }catch (Exception e){
            log.error("Project startup pulls out the question library from the database and inserts it into the cache Set In collection-An exception occurred:",e.fillInStackTrace());
        }
    }

    //TODO: Get a random, disordered list of questions from the cache
    public Set<Problem> getRandomEntitys(Integer total){
        Set<Problem> problems=Sets.newHashSet();
        try {
            SetOperations<String,Problem> setOperations=redisTemplate.opsForSet();
            problems=setOperations.distinctRandomMembers(Constant.RedisSetProblemsKey,total);
        }catch (Exception e){
            log.error("Get a random, disordered list of questions from the cache-An exception occurred:",e.fillInStackTrace());
        }
        return problems;
    }
}

(3) After that, we need to develop a request method in SetController that implements "After successful login of the test generation, get random, disordered and unique N-channel titles from the Set of cache collections", the complete source code of which is as follows:

    //TODO: Remove (not remove) the Random Questions Library - a fixed number of random test questions
    @RequestMapping(value = "problems/random",method = RequestMethod.GET)
    public BaseResponse getRandomProblems(@RequestParam Integer total){
        if (total<=0){
            return new BaseResponse(StatusCode.InvalidParams);
        }
        BaseResponse response=new BaseResponse(StatusCode.Success);
        try {
            response.setData(setService.getRandomProblems(total));

        }catch (Exception e){
            response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }

Where setService.getRandomProblems(total) is "Get a random list of total titles from the Set of cache collections", the source code is as follows:

    //TODO: Remove a fixed number of random, disordered test lists from the question library
    public Set<Problem> getRandomProblems(Integer total) throws Exception{
        return problemService.getRandomEntitys(total);
    }

Ultimately, you will find that "Barabara has said a lot before, and the core focus is just to call this API/method from SetOperations:"

setOperations.distinctRandomMembers(Constant.RedisSetProblemsKey,total);

This corresponds to the SRAMDMEMBER command Set in Redis!The function and usage of this command have been described in the previous article, as shown in the following figure:

Finally, we open Postman and test it in a wave, as shown in the following figures:

Okay, we've covered this article. I suggest you follow the example code provided in this article. Only after you have passed this article can you know how useful this is, otherwise you will become a "chatter"!

Partners interested in Redis related technology stacks and real-world scenarios can go to the course center of the technical community set up by debug to learn and watch: Programmer Field Base !Other related technologies, interested partners can focus on the technical public number of debug at the bottom to learn and grow together!

Supplement:

1. The related source code involved in this article can be check ed out at this address for viewing and learning: https://gitee.com/steadyjack/SpringBootRedis

2. At present debug has compiled and recorded a video tutorial about the content in this article, and interested little partners can go to watch and learn: https://edu.csdn.net/course/detail/26619

3. Focus on debug's public number of WeChat. The latest technical articles, courses and technical columns will be published on the public number at the first time.

132 original articles published, 239 praised, 610,000 visits+
His message board follow

Tags: Database Redis less supervisor

Posted on Fri, 07 Feb 2020 18:49:51 -0800 by bongbong