Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to learn string commands through log cases

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces you how to learn string commands through log cases, the content is very detailed, interested friends can refer to, I hope it can be helpful to you.

The editor will talk about string type commands in Redis through a small demo. Demo will use springboot as the background framework for rapid development, iview front-end framework for simple page design, in order to facilitate the use of DB to store data, directly use Redis as storage.

The usage of springboot and the project building part will not be discussed in this article. Directly according to the functional aspects of the story, interspersed with string command instructions.

Case

The demo function is to log, and the general page of the whole demo is as follows

Preparatory work

First define a prefix for key, which has stored the key of the self-incremented id

Private static final String MY_LOG_REDIS_KEY_PREFIX = "myLog:"; private static final String MY_LOG_REDIS_ID_KEY = "myLogID"

Log related key will be stored in the form of myLog:1, myLog:2 and myLog:3

Redis Operand

Private RedisTemplate redisTemplate;//string Command Operand private ValueOperations valueOperations; added

Let's take a look at the gif diagram first.

Let's take a look at the backstage method.

@ RequestMapping (value = "/ addMyLog", method = RequestMethod.POST) public boolean addMyLog (@ RequestBody JSONObject myLog) {/ / get self-increment id Long myLogId = valueOperations.increment (MY_LOG_REDIS_ID_KEY, 1); String date = LocalDateTime.now (). Format ("yyyy-MM-dd HH:mm:ss"); myLog.put ("id", myLogId); myLog.put ("createDate", date); myLog.put ("updateDate", date) / / write data to redis valueOperations.set (MY_LOG_REDIS_KEY_PREFIX+myLogId, myLog.toString ()); return true;}

From the above code, you can see that there are two places where redis is operated.

ValueOperations.increment (MY_LOG_REDIS_ID_KEY, 1)

ValueOperations.set (MY_LOG_REDIS_KEY_PREFIX+myLogId, myLog.toString ())

Command introduction

ValueOperations.increment is actually equivalent to INCR, INCRBY, INCRBYFLOAT, DECR and DECRBY in Redis.

INCR

INCR key

Performs an atomic plus one operation on the value stored in the specified key. If there is no corresponding key, it is set to 0, and then added.

INCRBY

INCRBY key increment

In fact, it is similar to INCR, except that this command specifies how much to add.

INCRBYFLOAT

INCRBYFLOAT key increment

It's similar, except that the added value is a floating point number.

Incrbyfloat incrByFloatKey 5.11incrbyfloat incrByFloatKey 5.22

The execution result is as follows

Here is the java code

@ Testpublic void incrByFloat () {System.out.println (jedis.incrByFloat ("incrByFloatKey", 5.11)); System.out.println (redisTemplate.opsForValue () .increment ("incrByFloatKey", 5.22));}

The opposite commands to INCR are DECR and DECRBY, so I won't cover them here.

ValueOperations.set corresponds to the SET command of Redis, as well as SETEX, SETNX, and PSETEX. It should be noted that set provides EX, PX, NX, and XX parameters in Redis version 2.6.12 to replace SETEX, SETNX, and PSETEX, and subsequent versions may remove SETEX, SETNX, and PSETEX commands. Here are the exact words from the official website.

Since the SET command options can replace SETNX, SETEX, PSETEX, it is possible that in future versions of Redis these three commands will be deprecated and finally removed.

SET

SET key value [expiration EX seconds | PX milliseconds] [NX | XX]

Setting key key corresponds to value

Parameter option

EX seconds-sets the expiration time of the key key (in hours and seconds)

PX milliseconds-sets the expiration time of the key key (in milliseconds)

NX-the value of key is set only if the key key does not exist

XX-the value of key is set only if the key key exists

SETRANGE

SETRANGE key offset value

Replace characters starting from a specified length

Set setRangeKey "Hello World" setrange setRangeKey 6 "Redis" get setRangeKey

The execution result is as follows

Here is the java code

@ Testpublic void setRange () {jedis.set ("setRangeKey", "Hello World"); jedis.setrange ("setRangeKey", 6, "Redis"); System.out.println (jedis.get ("setRangeKey")); / / spring redisTemplate.opsForValue () .set ("setRangeKey", "learyRedis", 6); System.out.println (redisTemplate.opsForValue (). Get ("setRangeKey"));}

MSET

MSET key value [key value...]

Set multiple key and value at the same time

MSETNX

MSETNX key value [key value...]

Ignore if multiple key and value,key are set at the same time

Query

Then write a query method to query the new content.

@ RequestMapping (value = "/ getMyLog", method = RequestMethod.GET) public List getMyLog () {/ / get the keys Set myLogKeys of mylog = redisTemplate.keys ("myLog:*"); return valueOperations.multiGet (myLogKeys);}

Both lines in the method involve Redis operations, first getting the myLog:*-related key collection through the keys command, and then getting the record through the multiGet method (that is, the mget command).

Command introduction

KEYS

KEYS pattern

Find all key that match a given pattern pattern (regular expression)

GET

GET key

Get the value corresponding to key

Set getKey getValueget getKey

The execution result is as follows

GETRANGE

GETRANGE key start end

Get the characters between start and end

Set getRangeKey "Hello learyRedis" getrange getRangeKey 6-1getrange getRangeKey 0-12

The execution result is as follows

GETSET

GETSET key value

Set the new value for key and return the value for the original key

Getset getSetKey newValueset getSetKey valuegetset getSetKey newValueget getSetKey

The execution result is as follows

MGET

MGET key [key...]

Returns the value of all specified key

Mset mGetKey1 mGetValue1 mGetKey2 mGetValue2 mGetKey3 mGetValue3mget mGetKey1 mGetKey2 mGetKey3 mGetKey4

The execution result is as follows

Let's look at the code.

@ RequestMapping (value = "/ updateMyLog", method = RequestMethod.POST) public boolean updateMyLog (@ RequestBody JSONObject myLog) {String myLogId = myLog.getString ("id"); myLog.put ("updateDate", LocalDateTime.now (). Format (DateTimeFormatter.ofPattern ("yyyy-MM-dd HH:mm:ss")); valueOperations.set (MY_LOG_REDIS_KEY_PREFIX+myLogId, myLog.toString ()); return true;}

The set here is described in the new method, so let's take a look at the APPEND and STRLEN commands

Command introduction

APPEND

APPEND key value

Append a new value to the tail of the value

The command executed by the redis client is as follows

Append appendKey appendappend appendKey Valueget appendKey

The execution result is as follows

The code is as follows

@ RequestMapping (value = "/ delMyLog/ {id}", method = RequestMethod.DELETE) public boolean delMyLog (@ PathVariable String id) {return redisTemplate.delete (MY_LOG_REDIS_KEY_PREFIX + id);}

You can see that only the delete method is used in the code, corresponding to the Redis DEL command (which belongs to the basic command)

Command introduction

DEL

DEL key [key...]

Delete key

BIT related commands

Bit commands include SETBIT, GETBIT, BITCOUNT, BITFIELD, BITOP, BITPOS and so on.

The command will not be introduced here, but will directly talk about the cases related to bit.

Pattern: real time metrics using bitmaps

BITOP is a good complement to the pattern documented in the BITCOUNT command documentation. Different bitmaps can be combined in order to obtain a target bitmap where the population counting operation is performed.

See the article called "Fast easy realtime metrics using Redis bitmaps" >

Case address Fast easy realtime metrics using Redis bitmaps

There are also many online translations. Baidu or google can be used if you need it.

Here is a rough description of the use of bitmap method to calculate the number of daily login users, weekly continuous login users and monthly continuous login users

Bitmap method is the abbreviation of bitmap, the so-called bitmap, is to use each bit to store a certain state, suitable for large-scale data, but the data state is not many cases. It is usually used to determine whether a certain data exists. -from Baidu encyclopedia

It's as if int in java has 4 bytes, or 32 bits. When all 32 bits are 1, that is the maximum value of int.

Bit can only be set to bit 0 or 1, that is, binary.

BitSet can be used to manipulate bit-related operations in java

Scene

There are 10, 000 users, with id ranging from 1 to 10000, depending on whether the ID bit is 1 or 0, depending on whether it is currently online. Through the daily records to count the continuous online situation of users.

Analysis.

Number one is online with id 5, 3, 1, 2 with id 5, 4, 3, and 3 with id 3, 2, 1. The stored data is as follows

Serial number: 5 4 3 2 10 1: 1 0 1 0 10 2: 1 11 0 0 3: 0 0 1 1 10

Then we can only carry out and operate the data for three days to know which ones have been online for three days in a row, and the results of the operation are as follows

Serial number: 5 4 3 2 1 0 result: 0 010 0 0

It is obvious that users with an id of 3 have logged in for three consecutive days.

Code

Define some constants first

/ / stored key prefix private static final String ONLINE_KEY_PREFIX = "online:"; / / number of days private static final int DAY_NUM = 30 private static final int PEOPLE_NUM / number of users private static final int PEOPLE_NUM = 10000

Then simulate a month's data.

Public void createData () {/ / is used to ensure that the thread finishes performing subsequent operations CountDownLatch countDownLatch = new CountDownLatch (DAY_NUM); int poolSize = Runtime.getRuntime (). AvailableProcessors () * 2; ThreadPoolExecutor executor = new ThreadPoolExecutor (poolSize, poolSize, 60, TimeUnit.SECONDS, new ArrayBlockingQueue (DAY_NUM-poolSize)); / / DAY_ NUM day for (int I = 1 I {/ / suppose there are PEOPLE_NUM users for (int j = 1; j 0.1);} countDownLatch.countDown ();});} / / wait for the thread to complete try {countDownLatch.await ();} catch (InterruptedException e) {e.printStackTrace ();}}

And finally, statistics.

Public void calActive (int day) {if (day)

< 0 || day >

DAY_NUM) {throw new IllegalArgumentException ("the number of days passed cannot be less than 0 or more than 30 days!");} long calStart = System.currentTimeMillis (); BitSet active = new BitSet (); active.set (0, PEOPLE_NUM); for (int I = 1; I

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report