Highly available user registration solutions

“This is the 11th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

Hash structure in redis

The dictionary

  • The underlying dictionary implementation of Redis is based on a Hash table. A Hash table can have multiple Hash table nodes, and each Hash table node holds a key-value pair in the dictionary.
  • The internal structure of Redis Hash and Java HashMap is the same, that is, array + linked list structure. They just reHash differently.

Ziplist algorithm

Redis Hash Has an optimization algorithm for storage optimization called Ziplist (previously known as Zipmap).

The compression algorithm is optimized to save memory, and Ziplist is also used to optimize the storage of sorted sets and lists. When a hash is compressed into such a compressed set, it looks like this:

[key1, value1, key2, value2, …]

Hashes with some keys can be packaged into linear array structures while ensuring O(1) performance for get and set.

This approach does not maintain the O(1) performance guaranteed for GET and set as the hash field grows. As the hash grows, it is converted to a standard dictionary structure to maintain O(1) performance and the space saving feature is disabled. The Redis configuration parameter controls the conversion:

  • List-max-ziplist-entries: Default (512): Change to standard mode (dictionary) if hash growth exceeds this limit
  • List-max-ziplist-value: Default (64): Changes to standard mode (dictionary) when the maximum element in the hash exceeds this limit.

To save memory, it is recommended to use hashes instead of regular strings. This takes advantage of Redis's powerful hash features, so use hashes whenever possible. Small hashes will be encoded using small Spaces.

Redis Hash is a natural place to store these objects: session, user information, product information, configuration information, etc., and it is also the choice for caching large amounts of data.

The difference between String and Hash in redis

String stores user information, and the Hash structure stores user information separately for each field. Therefore, you can obtain partial field information during query, saving network traffic.

  • Suitable for String storage:
    • You need to access a large number of fields at a time
    • When the storage structure has multiple layers of nesting
  • Where Hash storage is appropriate:
    • Stores a large amount of cached information. The hash structure uses less memory than the string structure
    • In most cases, only a few fields need to be accessed
    • You always know which fields are available in case you don’t get the data you want when you use MGET
  • Store Java Bean objects for business profiling

3. Redis technical solution for registering micro-blog

Graph LR users - > registration | | DB DB - > | | storage redis redis - > | | storage way Hash structure

Note: Each hash can store 2 (32-1) square key-value pairs (over 4 billion)

Four, SpringBoot+Redis microblogging registration

Step 1: Create the user table

DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL DEFAULT ' ' COMMENT 'Username',
  `password` varchar(50) NOT NULL DEFAULT ' ' COMMENT 'password',
  `sex` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Gender 0= female 1= male',
  `deleted` tinyint(4) unsigned NOT NULL DEFAULT '0' COMMENT 'Delete flag, default 0 not deleted, 1 deleted',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update Time',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation time'.PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='User table';

SET FOREIGN_KEY_CHECKS = 1;

Copy the code

Step 2: Register logic


@api (description = "user interface ")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @apiOperation (value=" @apiOperation ")
    @PostMapping(value = "/createUser")
    public void createUser(@RequestBody UserVO userVO) {
        User user=new User();
        BeanUtils.copyProperties(userVO,user);
        / / registeruserService.createUser(user); }}Copy the code
/** * weibo register */
public void createUser(User obj) {
    // Step 1: Enter the repository first
    this.userMapper.insertSelective(obj);
    // Step 2: After the database is successfully imported, write redis
    obj = this.userMapper.selectByPrimaryKey(obj.getId());
    // Convert attributes and values in Object to Map objects
    Map<String, Object> map = ObjectUtil.objectToMap(obj);
    // Set the cache key
    String key = Constants.CACHE_KEY_USER + obj.getId();

    // The storage of weibo users uses the hash of reids
    HashOperations<String, String, Object> opsForHash = redisTemplate.opsForHash();
    opsForHash.putAll(key, map);

    // Step 3: Set the expiration date to 30 days
    this.redisTemplate.expire(key, 30, TimeUnit.DAYS);
}
Copy the code

Note: this article discusses the use of redis hash structure scenarios, as for high availability and high concurrency code is not carefully considered, you can use Lua script instead of multiple Redis network requests, etc..

Redis distributed cache family

  • Redis Distributed Cache (1) – Redis Installation (Linux and Docker)
  • Redis Distributed cache (ii) – RDB and AOF
  • SpringBoot integrates Mybatis-Plus,Redis and Swagger
  • Redis distributed cache (4) – SpringCache integrates redis
  • Redis Distributed Cache (5) — Common command (String)
  • Redis Distributed Cache (6) — Article read volume PV Solution (String)
  • Redis Distributed Cache (7) — Distributed Global ID Solution (String)
  • Redis Distributed Cache (8) — Highly Concurrent atomic Operations (Redis+Lua)
  • Redis Distributed Cache (9) — Hacker Anti-brush Attack Solution (String)
  • Redis Distributed Cache (10) common Commands (Hash)
  • Redis Distributed Cache (11) store Java Bean object Hash
  • Redis Distributed Cache (12) – Short Link Solution (Hash)
  • Redis Distributed Cache (13) — JD Shopping cart solution
  • Redis distributed cache (14) – distributed session inconsistency solution
  • The article continues to be updated…