חיבור למופע Redis מאשכול Google Kubernetes Engine

אפשר להתחבר למכונה של Redis רק מאשכולות של Google Kubernetes Engine שמשתמשים באותה רשת מורשית כמו המכונה של Redis.

הגדרה

אם כבר התקנתם את Google Cloud CLI ויצרתם מכונת Redis, אתם יכולים לדלג על השלבים האלה.

  1. מתקינים את ה-CLI של gcloud ומפעילים אותו:

    gcloud init
    
  2. כדי ליצור מכונה של Redis, פועלים לפי המדריך למתחילים. שימו לב לאזור, לכתובת ה-IP וליציאה של מכונת Redis.

הכנת אשכול GKE

  1. אם לא יצרתם אשכול GKE, אתם יכולים ליצור אחד באמצעות הפקודות הבאות ל-Google Cloud CLI:

    1. מגדירים את הפרויקט לאפליקציה לדוגמה ב-gcloud.

      gcloud config set project PROJECT_ID

    2. מגדירים את משתנה התצורה של אזור Compute Engine ב-gcloud.

      gcloud config set compute/zone ZONE

    3. יוצרים אשכול GKE בשם visitcount-cluster.

      gcloud container clusters create visitcount-cluster --num-nodes=3 --enable-ip-alias

  2. אם לא יצרתם את האשכול באמצעות gcloud, השתמשו בפקודה הבאה כדי לאחזר את פרטי הכניסה של האשכול:

    gcloud container clusters get-credentials CLUSTER_NAME --zone CLUSTER_ZONE --project PROJECT_ID
    1. ‫CLUSTER_NAME הוא השם של אשכול GKE.
    2. ‫CLUSTER_ZONE הוא האזור שבו נמצא האשכול.
    3. ‫PROJECT_ID הוא הפרויקט שבו נמצאים האשכול ומכונות Redis.
  3. אם גרסת האשכול היא 1.8 ואילך וגם מופעלים בו כתובות IP חלופיות, אפשר לדלג על השלב הזה. אם גרסת האשכול היא 1.7 או גרסה קודמת, או אם גרסת האשכול היא 1.8 או גרסה מתקדמת יותר וכתובות ה-IP החלופיות לא מופעלות, צריך לבצע את השלבים הבאים לפני שמנסים להתחבר למכונה.

    1. מריצים את הפקודות הבאות, ומחליפים את RESERVED_IP_RANGE בטווח כתובות ה-IP השמורות של המכונה:

      git clone https://github.com/bowei/k8s-custom-iptables.git
      cd k8s-custom-iptables/
      TARGETS="RESERVED_IP_RANGE" ./install.sh
      cd ..
      
    2. אם אתם לא יודעים מהו טווח כתובות ה-IP השמורות של המכונה, תוכלו למצוא אותו באמצעות המסוף (אפשרויות מתקדמות) או באמצעות הפקודה הבאה:

      gcloud redis instances describe INSTANCE_ID --region=REGION
      

    למידע נוסף על כתובות IP חלופיות, כולל איך ליצור אשכול כשההגדרה הזו מופעלת, קראו את המסמכים בנושא כתובות IP חלופיות.

אפליקציה לדוגמה

אפליקציית השרת לדוגמה הזו ב-HTTP יוצרת חיבור למכונה של Redis מאשכול של Google Kubernetes Engine.

משכפלים את המאגר של שפת התכנות שבחרתם ועוברים לתיקייה שמכילה את הקוד לדוגמה:

המשך

git clone https://github.com/GoogleCloudPlatform/golang-samples
cd golang-samples/memorystore/redis

Java

git clone https://github.com/GoogleCloudPlatform/java-docs-samples
cd java-docs-samples/memorystore/redis

Node.js

git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples
cd nodejs-docs-samples/memorystore/redis

Python

git clone https://github.com/GoogleCloudPlatform/python-docs-samples
cd python-docs-samples/memorystore/redis

האפליקציה לדוגמה הזו מגדילה את מונה Redis בכל פעם שמתבצעת גישה לנקודת הקצה /.

המשך

האפליקציה הזו משתמשת בלקוח github.com/gomodule/redigo/redis. כדי להתקין אותו, מריצים את הפקודה הבאה:

go get github.com/gomodule/redigo/redis@latest

דוגמה לאפליקציה:


// Package main is a basic app that connects to a managed Redis instance.
package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/gomodule/redigo/redis"
)

var redisPool *redis.Pool

func incrementHandler(w http.ResponseWriter, r *http.Request) {
	conn := redisPool.Get()
	defer conn.Close()

	counter, err := redis.Int(conn.Do("INCR", "visits"))
	if err != nil {
		http.Error(w, "Error incrementing visitor counter", http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "Visitor number: %d", counter)
}

func main() {
	redisHost := os.Getenv("REDISHOST")
	redisPort := os.Getenv("REDISPORT")
	redisAddr := fmt.Sprintf("%s:%s", redisHost, redisPort)

	const maxConnections = 10
	redisPool = &redis.Pool{
		MaxIdle: maxConnections,
		Dial:    func() (redis.Conn, error) { return redis.Dial("tcp", redisAddr) },
	}

	http.HandleFunc("/", incrementHandler)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("Listening on port %s", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}

Java

האפליקציה הזו מבוססת על servlet של Jetty 3.1.

הוא משתמש בספרייה Jedis:

<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>5.1.0</version>
</dependency>

הכיתה AppServletContextListener משמשת ליצירת מאגר חיבורים ל-Redis לטווח ארוך:


package com.example.redis;

import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@WebListener
public class AppServletContextListener implements ServletContextListener {

  private Properties config = new Properties();

  private JedisPool createJedisPool() throws IOException {
    String host;
    Integer port;
    config.load(
        Thread.currentThread()
            .getContextClassLoader()
            .getResourceAsStream("application.properties"));
    host = config.getProperty("redis.host");
    port = Integer.valueOf(config.getProperty("redis.port", "6379"));

    JedisPoolConfig poolConfig = new JedisPoolConfig();
    // Default : 8, consider how many concurrent connections into Redis you will need under load
    poolConfig.setMaxTotal(128);

    return new JedisPool(poolConfig, host, port);
  }

  @Override
  public void contextDestroyed(ServletContextEvent event) {
    JedisPool jedisPool = (JedisPool) event.getServletContext().getAttribute("jedisPool");
    if (jedisPool != null) {
      jedisPool.destroy();
      event.getServletContext().setAttribute("jedisPool", null);
    }
  }

  // Run this before web application is started
  @Override
  public void contextInitialized(ServletContextEvent event) {
    JedisPool jedisPool = (JedisPool) event.getServletContext().getAttribute("jedisPool");
    if (jedisPool == null) {
      try {
        jedisPool = createJedisPool();
        event.getServletContext().setAttribute("jedisPool", jedisPool);
      } catch (IOException e) {
        // handle exception
      }
    }
  }
}

הכיתה VisitCounterServlet היא servlet של אינטרנט שמגדיל מונה של Redis:


package com.example.redis;

import java.io.IOException;
import java.net.SocketException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@WebServlet(name = "Track visits", value = "")
public class VisitCounterServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {
      JedisPool jedisPool = (JedisPool) req.getServletContext().getAttribute("jedisPool");

      if (jedisPool == null) {
        throw new SocketException("Error connecting to Jedis pool");
      }
      Long visits;

      try (Jedis jedis = jedisPool.getResource()) {
        visits = jedis.incr("visits");
      }

      resp.setStatus(HttpServletResponse.SC_OK);
      resp.getWriter().println("Visitor counter: " + String.valueOf(visits));
    } catch (Exception e) {
      resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
  }
}

Node.js

האפליקציה הזו משתמשת במודול redis. קובץ package.json לדוגמה:

{
  "name": "memorystore-redis",
  "description": "An example of using Memorystore(Redis) with Node.js",
  "version": "0.0.1",
  "private": true,
  "license": "Apache Version 2.0",
  "author": "Google Inc.",
  "engines": {
    "node": ">=20.0.0"
  },
  "dependencies": {
    "redis": "^4.0.0"
  }
}

קוד אפליקציה לדוגמה:

'use strict';
const http = require('http');
const redis = require('redis');

const REDISHOST = process.env.REDISHOST || 'localhost';
const REDISPORT = process.env.REDISPORT || 6379;

const client = redis.createClient({
  url: `redis://${REDISHOST}:${REDISPORT}`,
});

client.on('error', err => console.error('ERR:REDIS:', err));

client
  .connect()
  .then(() => {
    console.log('Connected to Redis');
    http
      .createServer(async (req, res) => {
        try {
          const reply = await client.incr('visits');
          res.writeHead(200, {'Content-Type': 'text/plain'});
          res.end(`Visitor number: ${reply}\n`);
        } catch (err) {
          console.error(err);
          res.statusCode = 500;
          res.end(err.message);
        }
      })
      .listen(8080, () => {
        console.log('Server listening on port 8080');
      });
  })
  .catch(err => {
    console.error('Failed to connect to Redis:', err);
    throw err;
  });

Python

האפליקציה הזו משתמשת ב-Flask להצגת דפי אינטרנט ובחבילה redis-py כדי לתקשר עם המכונה של Redis.

Flask==3.1.3; python_version >= '3.9'
gunicorn==23.0.0
redis==6.0.0
Werkzeug==3.1.9; python_version >= '3.10'

קוד אפליקציה לדוגמה:

import logging
import os

from flask import Flask
import redis

app = Flask(__name__)

redis_host = os.environ.get("REDISHOST", "localhost")
redis_port = int(os.environ.get("REDISPORT", 6379))
redis_client = redis.StrictRedis(host=redis_host, port=redis_port)


@app.route("/")
def index():
    value = redis_client.incr("counter", 1)
    return f"Visitor number: {value}"


@app.errorhandler(500)
def server_error(e):
    logging.exception("An error occurred during a request.")
    return (
        """
    An internal error occurred: <pre>{}</pre>
    See logs for full stacktrace.
    """.format(
            e
        ),
        500,
    )


if __name__ == "__main__":
    # This is used when running locally. Gunicorn is used to run the
    # application on Google App Engine and Cloud Run.
    # See entrypoint in app.yaml or Dockerfile.
    app.run(host="127.0.0.1", port=8080, debug=True)

פיתוח קובץ האימג' של הקונטיינר

יוצרים את קובץ האימג' של הקונטיינר ומעבירים אותו בדחיפה ל-Container Registry באמצעות Cloud Build:

cp gke_deployment/Dockerfile .
gcloud artifacts repositories create --location REPO_REGION --repository-format=docker REPO_ID
gcloud builds submit --tag REPO_REGION-docker.pkg.dev/PROJECT_ID/REPO_ID/visit-counter:v1

פריסת האפליקציה ב-Google Kubernetes Engine

כדי להימנע מקידוד קשיח של כתובת ה-IP של מכונת Redis, אפשר ליצור redishost ConfigMap:

export REDISHOST_IP=REDISHOST_IP
kubectl create configmap redishost --from-literal=REDISHOST=${REDISHOST_IP}

מוודאים שההגדרה בוצעה באמצעות הפקודה הבאה:

kubectl get configmaps redishost -o yaml

מעדכנים את gke_deployment/visit-counter.yaml ומחליפים את <REPO_REGION>,‏ <PROJECT_ID> ו-<REPO_ID> בערכים של קובץ האימג' של הקונטיינר שיצרתם בקטע פיתוח קובץ האימג' של הקונטיינר. הקובץ הזה מכיל את ההגדרות של הפריסה והשירות.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: visit-counter
  labels:
    app: visit-counter
spec:
  replicas: 1
  selector:
    matchLabels:
      app: visit-counter
  template:
    metadata:
      labels:
        app: visit-counter
    spec:
      containers:
      - name: visit-counter
        image: "<REPO_REGION>-docker.pkg.dev/<PROJECT_ID>/<REPO_ID>/visit-counter:v1"
        env:
        - name: REDISHOST
          valueFrom:
            configMapKeyRef:
              name: redishost
              key: REDISHOST
        ports:
        - name: http
          containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: visit-counter
spec:
  type: LoadBalancer
  selector:
    app: visit-counter
  ports:
  - port: 80
    targetPort: 8080
    protocol: TCP

מחילים את ההגדרות על האשכול:

kubectl apply -f gke_deployment/visit-counter.yaml

כדי לזהות את כתובת ה-IP החיצונית של האפליקציה לדוגמה, מריצים את הפקודה הבאה:

kubectl get service visit-counter

כדי לוודא שהאפליקציה מתארחת בכתובת ה-IP החיצונית, משתמשים בדפדפן או שולחים בקשת GET באמצעות curl או הדפדפן:

curl http://EXTERNAL_IP

הסרת הרשומה של טבלאות ה-IP של מכונת Redis

אם פעלתם לפי השלב השלישי בקטע הכנת אשכול GKE במדריך הזה, התקנתם את טווח כתובות ה-IP השמורות של מכונת Redis בטבלאות ה-IP של מכונת GKE. כדי להסיר את הרשומה של טווח כתובות ה-IP של Redis מטבלאות ה-IP של מכונת GKE, מריצים את הפקודה הבאה מהספרייה k8s-custom-iptables/:

./uninstall.sh