# Redis

## Introduction

* It is store the data temporarily and obtain the data quickly from the server-side, as the data is stored in ram instead of hard disk in key-value pair
* Traditionally, obtain the data from database is slower, as it is required to scan the table, there will be a delay, apart from that, multiple requests to obtain the data from database is not an ideal case
* Sometimes, we want the real-time data or do caching , we can make good use of redis to do it

## Caching Strategy

<figure><img src="https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2FauQRuF7RL8g4dM9aST1j%2Fimage.png?alt=media&#x26;token=3a695a72-4c50-4272-998e-4d5669cafc87" alt=""><figcaption></figcaption></figure>

## Data Type

### String

* A string in Redis can be up to 512MB in size. Its operation is atomic to prevent from inconsistency when facing multiple access

```javascript
const res1 = await client.set("bike:1", "Deimos");
console.log(res1);  // OK
const res2 = await client.get("bike:1");
console.log(res2);  // Deimos
```

### List

* [Redis List](https://www.alibabacloud.com/en/product/apsaradb-for-redis?_p_lc=1)s are simply lists of strings, sorted by [insertion order](https://www.alibabacloud.com/help/en/doc-detail/130409.html). They are implemented under the hood using linked lists. This makes it easy to add elements to the beginning or end of the list in constant time.&#x20;
* The key features of Redis lists are their ability to perform push and pop [operations](https://www.alibabacloud.com/en/solutions/mobile/operation?_p_lc=1), access elements by index, and more.

<pre class="language-javascript"><code class="lang-javascript"><strong>// first in, first out
</strong><strong>const res1 = await client.lPush('bikes:repairs', 'bike:1');
</strong>console.log(res1);  // 1

const res2 = await client.lPush('bikes:repairs', 'bike:2');
console.log(res2);  // 2

const res3 = await client.rPop('bikes:repairs');
console.log(res3);  // bike:1

const res4 = await client.rPop('bikes:repairs');
console.log(res4);  // bike:2

// first in, last out
const res5 = await client.lPush('bikes:repairs', 'bike:1');
console.log(res5);  // 1

const res6 = await client.lPush('bikes:repairs', 'bike:2');
console.log(res6); // 2

const res7 = await client.lPop('bikes:repairs');
console.log(res7);  // bike:2

const res8 = await client.lPop('bikes:repairs');
console.log(res8);  // bike:1
</code></pre>

### Hash

* Redis Hashes are perfect for representing objects.  They are a collection of key-value pairs.&#x20;
* Redis Hashes are ideal for storing structured data, like an object with many fields.

```javascript
const res1 = await client.hSet(
  'bike:1',
  {
    'model': 'Deimos',
    'brand': 'Ergonom',
    'type': 'Enduro bikes',
    'price': 4972,
  }
)
console.log(res1) // 4

const res2 = await client.hGet('bike:1', 'model')
console.log(res2)  // 'Deimos'

const res3 = await client.hGet('bike:1', 'price')
console.log(res3)  // '4972'

const res4 = await client.hGetAll('bike:1')
console.log(res4)  
```

### Set

* Redis Sets are an unordered collection of strings. They support a variety of commands that perform operations based on set theory

```javascript
const res1 = await client.sAdd('bikes:racing:france', 'bike:1')
console.log(res1)  // >>> 1

const res2 = await client.sAdd('bikes:racing:france', 'bike:1')
console.log(res2)  // >>> 0
const res3 = await client.sAdd('bikes:racing:france', ['bike:2', 'bike:3'])
console.log(res3)  // >>> 2
const res4 = await client.sAdd('bikes:racing:usa', ['bike:1', 'bike:4'])
console.log(res4)  // >>> 2
```

### Sorted Set

* [Redis Sorted](https://www.alibabacloud.com/en/product/apsaradb-for-redis?_p_lc=1) Sets, or ZSets, are similar to Redis Sets with an unique feature&#x20;
* Each member of a Sorted Set is associated with a score. This score is used to sort the set members from the smallest to the largest score and and search the result based on the score.  The members in a Sorted Set are unique, but the scores may be repeated.&#x20;
* Sorted Sets are particularly useful for tasks that require maintaining a list sorted by a score. For example, they can be used to maintain a leaderboard in online games

```javascript
const res1 = await client.zAdd('racer_scores', { score: 10, value: 'Norem' });
console.log(res1);  // >>> 1

const res2 = await client.zAdd('racer_scores', { score: 12, value: 'Castilla' });
console.log(res2);  // >>> 1

const res3 = await client.zAdd('racer_scores', [
  { score: 8, value: 'Sam-Bodden' },
  { score: 10, value: 'Royce' },
  { score: 6, value: 'Ford' },
  { score: 14, value: 'Prickett' },
  { score: 12, value: 'Castilla' }
]);
console.log(res3);  // >>> 4
//  get all the racers with 10 or fewer points.
const res4 = await client.zRangeByScore('racer_scores', '-inf', 10);
console.log(res4);
// >>> ['Ford', 'Sam-Bodden', 'Norem', 'Royce']
```

## Mode

### Master-Slave Replication

<figure><img src="https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2FGmkb45QJ8ifryJMudCH5%2Fimage.png?alt=media&#x26;token=f0925f01-6bc5-4970-931b-29fe40cecdae" alt=""><figcaption></figcaption></figure>

* Include 1 master and multiple slaves
* Write and read can be conducted at master
* Slave is for read - only
* After the update of master, master will send snapshot to slave for data sync
* Master-slave mode requires manual intervention for failover. If the master node fails, a slave node must be promoted manually to become the new master, which can introduce some downtime and administrative overhead.

### Cluster Mode

<figure><img src="https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2FhW4WAvZsncBK02iAFFRL%2Fimage.png?alt=media&#x26;token=5da0afc7-4a34-433d-839f-2b11e7ae496a" alt=""><figcaption></figcaption></figure>

* Sharding. Each node is responsible for their slot (part of data)
* Enabling horizontal scaling
* Redis Cluster mode provides built-in support for high availability and fault tolerance. It uses a distributed consensus algorithm and automatic failover to ensure data availability even in the event of node failures. If one node is down, others will take its slot to prevent from downtime

## References

{% embed url="https://www.youtube.com/watch?v=G1rOthIU-uo" %}

{% embed url="https://blog.techbridge.cc/2016/06/18/redis-introduction/" %}
