LSX
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Redis in GCP **在GCP 的memorystore 中有4種機器類別** ![image](https://hackmd.io/_uploads/rkkrp1KrJg.png) **GCP 的4種記憶體型資料庫比較** ![image](https://hackmd.io/_uploads/HJvA6yFSkl.png) ## 建立機器 * 建立redis instance (因為是簡單使用而已,Basic 就夠) **後面會建立computer engine,兩個的region 必須相同** **redis 的費用不低,使用完記得刪除!!!(跟Cloud SQL 一樣)** ![image](https://hackmd.io/_uploads/SJXi1xtH1e.png) **提升可靠度(需選擇Standard 版本)** **網路需與後面的computer engine 相同** ![image](https://hackmd.io/_uploads/BkpSIQYB1l.png) **建立之後須等約5分鐘才會變成可運作狀態** **在等待期間先進行下一步** * Cloud SQL **基本上與之前相同** ![image](https://hackmd.io/_uploads/SJoqdxFH1x.png) **要給privateIP,才能讓redis對其連線** ![image](https://hackmd.io/_uploads/Syk9FeFH1g.png) * 進資料庫放一些資料 ```bash= gcloud sql connect cloudsql-instance --user=root ``` ```sql= CREATE DATABASE app_db; USE app_db; CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50), email VARCHAR(50) ); INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com'); INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com'), ('Charlie', 'charlie@example.com'), ('David', 'david@example.com'), ('Eva', 'eva@example.com'), ('Frank', 'frank@example.com'), ('Grace', 'grace@example.com'), ('Hannah', 'hannah@example.com'), ('Isaac', 'isaac@example.com'), ('Jack', 'jack@example.com'), ('Kathy', 'kathy@example.com'); ``` * 建立instance * 只有地區的地方需要注意要跟redis 位置一樣 **其他設定除了作業系統依自己使用習慣外皆預設即可** ![image](https://hackmd.io/_uploads/rJVpzeFB1l.png) * 使用GCP VM對其連線 (內網) **建起來的redis instance** ![image](https://hackmd.io/_uploads/rJzLNfFryx.png) * 進去VM 及安裝 ``` gcloud compute ssh proxy-vm --zone=asia-east1-a sudo apt update sudo apt install -y redis-tools ``` * 測試redis ```bash $ redis-cli -h 10.127.10.211 -p 6379 ping PONG # 回應PONG為正常啟用中 ``` * app_session.py ```python= import redis import uuid # Redis 配置 # 內網IP redis_client = redis.Redis(host='10.127.10.211', port=6379, decode_responses=True) # 建立 Session def create_session(user_id): session_id = str(uuid.uuid4()) redis_client.setex(f"session:{session_id}", 300, user_id) # 會話有效期為1小時 return session_id # 驗證 Session def get_user_from_session(session_id): return redis_client.get(f"session:{session_id}") # 測試 session_id = create_session('user_123') print("✅ 建立 Session ID:", session_id) user_id = get_user_from_session(session_id) print("📊 使用者 ID:", user_id) ``` * app_cache.py ```python= import redis import mysql.connector import time # Redis 配置 # redisIP redis_client = redis.Redis(host='10.127.10.211', port=6379, decode_responses=True) # Cloud SQL 配置 # SQL IP db_config = { 'host': '10.121.192.5', 'port': 3306, 'user': 'root', 'password': 'admin1234', 'database': 'app_db' } def get_user(user_id): """ 根據用戶 ID 獲取用戶資訊,先檢查 Redis 快取,未命中時從 MySQL 中獲取並存回 Redis。 """ cache_key = f"user:{user_id}" # Step 1: 檢查 Redis 快取 cached_user = redis_client.get(cache_key) if cached_user: print("✅ 從 Redis 快取取得用戶資訊") return cached_user print("❌ Redis 快取未命中,查詢 MySQL 資料庫...") # Step 2: 查詢 MySQL try: connection = mysql.connector.connect(**db_config) cursor = connection.cursor(dictionary=True) cursor.execute("SELECT id, name, email FROM users WHERE id = %s", (user_id,)) user = cursor.fetchone() cursor.close() connection.close() if user: user_data = f"{user['id']} - {user['name']} - {user['email']}" redis_client.setex(cache_key, 300, user_data) # 快取 5 分鐘 print("✅ 已將用戶資料存入 Redis 快取") return user_data else: print("❌ 查無此用戶") return None except mysql.connector.Error as err: print(f"❌ MySQL 錯誤: {err}") return None # 測試 user_id = 1 # 測試用戶 ID user_info = get_user(user_id) print("📊 用戶資訊:", user_info) ``` **如果要從外部連線進內部,需要架設一台虛擬機當作Proxy server 做Port Forward** 可以參考: [Day 30 — Terraform/GCP實戰:使用 GCP Console 創建 GCP 資料庫服務Cloud MemoryStore — Redis](https://ithelp.ithome.com.tw/articles/10339791)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully