etc

redis cache

dev_summer 2022. 11. 13. 15:15

 

๋ฌธ์ œ์ •์˜ : 

 - ๋ฐ˜๋ณต์ ์ธ get์ž‘์—…์œผ๋กœ ์ธํ•œ DB ๋ถ€ํ•˜ ๋ฐœ์ƒ

 

ํ•ด๊ฒฐ๋ฐฉ๋ฒ• :

 - ๋ฐ˜๋ณต์ ์œผ๋กœ ์˜ค๋Š” get ์š”์ฒญ ์‹œ db์— ์ ‘์†ํ•˜์ง€์•Š๊ณ  redis์— ์ €์žฅํ•˜์—ฌ ๋ถˆ๋Ÿฌ์˜ด.

 

 

- redis.ts

import {createClient} from "@redis/client";

export class Redis {
  public static async getValue(key: string): Promise<any> {
    let result = null;
    try {
      const client = createClient();
      client.on("error", err => console.log("Redis Client Error", err));
      await client.connect();

      result = await client.get(key);

      await client.disconnect();
    } catch (e) {
      console.log(e);
    } finally {
      return result;
    }
  }

  public static async setValue(key: string, result: string) {
    try {
      const client = createClient();
      client.on("error", err => console.log("Redis Client Error", err));
      await client.connect();

      await client.set(key, result, {EX: 10});

      await client.disconnect();
    } catch (e) {
      console.log(e);
    } finally {
      return result;
    }
  }
}

 

- service.ts

async getBanners(){
	// redis์— banner list๊ฐ€ ์žˆ๋Š”์ง€ ๊ฒ€์‚ฌ 
    const cacheData = await Redis.getValue("getBanners");
    
    // ์žˆ์œผ๋ฉด ์บ์‹œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ 
    if (cacheData) {
      return JSON.parse(cacheData);
    }

	// ๋ฐฐ๋„ˆ๋ฆฌ์ŠคํŠธ ๋ถˆ๋Ÿฌ์˜ค๋Š” ์„œ๋น„์Šค์‹คํ–‰
 	...
    
	// ๋ฐฐ๋„ˆ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ์ „ redis์— ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅ
	await Redis.setValue("getBanners", JSON.stringify(banners));
    
    return banners;
}

'etc' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

docker๋กœ mysql๋„์šฐ๊ธฐ  (0) 2023.01.30
11์›” ์ธํ”„๋Ÿฐ ํ‡ด๊ทผ๊ธธ ๋ฐ‹-์—… #01 Node.js  (0) 2022.12.02
UNITHON 9th ํ›„๊ธฐ  (1) 2022.09.07
2022 ์ธํ”„์ฝ˜ ํ›„๊ธฐ  (1) 2022.08.28