Go 1.11은 지원이 종료되었으며 2026년 1월 31일에
지원 중단됩니다. 지원 중단 후에는 조직에서 이전에 조직 정책을 사용하여 레거시 런타임의 배포를 다시 사용 설정한 경우에도 Go 1.11 애플리케이션을 배포할 수 없습니다. 기존 Go 1.11 애플리케이션은
지원 중단 날짜 이후에도 계속 실행되고 트래픽을 수신합니다.
지원되는 최신 Go 버전으로 마이그레이션하는 것이 좋습니다.
Memorystore로 데이터 캐싱
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
확장 가능한 고성능 웹 애플리케이션은 특정 태스크에 대해 분산형 메모리 내 데이터 캐시를 견고한 영구 스토리지 앞에 두거나 아예 대체하여 사용하는 경우가 많습니다.
Redis용 Memorystore를 캐싱 서비스로 사용하는 것이 좋습니다.
Memorystore for Redis는 무료 등급을 제공하지 않습니다.
자세한 내용은
Memorystore 가격 책정을 참조하세요.
시작하기 전에 앱이 Memorystore for Redis 할당량 내에 있는지 확인합니다.
메모리 캐시를 사용하는 경우
세션 데이터, 사용자 환경설정, 웹페이지의 쿼리를 통해 반환되는 기타 데이터도 캐시하기에 적절한 대상입니다. 일반적으로 자주 실행되는 쿼리가 앱에 즉시 표시할 필요가 없는 일련의 결과를 반환하는 경우 이 결과를 캐시할 수 있습니다. 후속 요청에서는 캐시를 확인하여 결과가 없거나 만료된 경우에만 데이터베이스를 쿼리합니다.
다른 영구 스토리지에 백업하지 않고 Memcache에만 값을 저장할 경우 값이 만료되어 캐시에서 삭제되면 애플리케이션이 정상적으로 동작하는지 확인해야 합니다. 예를 들어 사용자의 세션 데이터가 갑자기 사라져서 세션이 오작동하는 경우 세션 데이터를 Memorystore 외에 데이터베이스에도 저장해야 합니다.
Memorystore 권한 이해하기
Google Cloud 서비스와의 모든 상호작용은 승인을 받아야 합니다. 예를 들어 Memorystore에서 호스팅되는 Redis 데이터베이스와 상호작용하려면 앱에서 Memorystore에 액세스하도록 승인된 계정의 사용자 인증 정보를 제공해야 합니다.
기본적으로 앱은 앱과 동일한 프로젝트에 있는 데이터베이스에 액세스하도록 승인된 App Engine 기본 서비스 계정의 사용자 인증 정보를 제공합니다.
다음 조건 중 하나라도 해당하는 경우 사용자 인증 정보를 명시적으로 제공하는 대체 인증 기술을 사용해야 합니다.
대체 인증 기술에 대한 자세한 내용은 서버 간 프로덕션 애플리케이션용 인증 설정을 참조하세요.
Memorystore 사용 개요
앱에서 Memorystore를 사용하려면 다음 안내를 따르세요.
Memorystore for Redis를 설정합니다. 이를 위해서는 Memorystore에 Redis 인스턴스를 만들고 앱에서 Redis 인스턴스와 통신하는 데 사용하는 서버리스 VPC 액세스를 만들어야 합니다. 이 두 독립 항목을 만드는 과정은 엄격한 순서를 따르지 않으며 어떤 순서로든 설정할 수 있습니다. 이 가이드의 안내에서는 먼저 서버리스 VPC 액세스를 설정하는 방법을 보여줍니다.
Redis용 클라이언트 라이브러리를 설치하고 Redis 명령어를 사용하여 데이터를 캐시합니다.
Memorystore for Redis는 모든 Redis용 클라이언트 라이브러리와 호환됩니다.
이 가이드에서는 redigo 클라이언트 라이브러리를 사용하여 앱에서 Redis 명령어를 전송하는 방법을 설명합니다.
업데이트를 테스트합니다.
App Engine에 앱을 배포합니다.
Memorystore for Redis 설정
Memorystore for Redis를 설정하려면 다음 안내를 따르세요.
App Engine을 VPC 네트워크에 연결합니다. 앱은 VPC 커넥터를 통해서만 Memorystore와 통신할 수 있습니다.
앱에서 커넥터를 사용하도록 구성의 설명대로 VPC 연결 정보를 app.yaml
파일에 추가해야 합니다.
만들려는 Redis 인스턴스의 IP 주소와 포트 번호를 기록합니다.
이 정보는 코드에서 Redis 클라이언트를 만들 때 사용됩니다.
Memorystore에서 Redis 인스턴스를 만듭니다.
Redis 인스턴스의 리전을 선택하라는 메시지가 표시되면 App Engine 앱이 있는 리전과 동일한 리전을 선택합니다.
종속 항목 설치
App Engine에서 앱을 실행할 때 redigo 클라이언트 라이브러리를 앱에서 사용할 수 있도록 만들려면 라이브러리를 앱의 종속 항목에 추가합니다. 예를 들어
go.mod
파일을 사용하여 종속 항목을 선언하려면 다음 줄을
go.mod
파일에 추가합니다.
module github.com/GoogleCloudPlatform/golang-samples/tree/master/memorystore/redis
Go 앱의 종속 항목 지정에 대해 자세히 알아보세요.
Redis 클라이언트 만들기
Redis 데이터베이스와 상호작용하려면 코드에서 Redis 클라이언트를 만들어 Redis 데이터베이스에 대한 연결을 관리해야 합니다. 다음 섹션에서는 redigo 클라이언트 라이브러리를 사용하여 Redis 클라이언트를 만드는 방법을 설명합니다.
환경 변수 지정
redigo 클라이언트 라이브러리는 환경 변수 2개를 사용하여 Redis 데이터베이스의 URL을 어셈블합니다.
- Memorystore에 만든 Redis 데이터베이스의 IP 주소를 식별하는 변수입니다.
- Memorystore에 만든 Redis 데이터베이스의 포트 번호를 식별하는 변수입니다.
이러한 변수를 코드에서 직접 정의하는 대신 앱의 app.yaml
파일에서 정의하는 것이 좋습니다. 이렇게 하면 로컬 환경 및 App Engine과 같은 다양한 환경에서 앱을 간편하게 실행할 수 있습니다.
예를 들어
app.yaml
파일에 다음 줄을 추가합니다.
env_variables:
REDISHOST: '10.112.12.112'
REDISPORT: '6379'
redigo 가져오기 및 클라이언트 만들기
REDISHOST
및
REDISPORT
환경 변수를 정의한 후 다음 줄을 사용하여 redigo 라이브러리를 가져오고 연결 풀을 만든 후 풀에서 Redis 클라이언트를 검색합니다.
Redis 명령어를 사용하여 캐시에 데이터 저장 및 검색
Memorystore Redis 데이터베이스는 대부분의 Redis 명령어를 지원하지만 그 중 몇 가지 명령어만 사용하여 캐시에서 데이터를 저장 및 검색해야 합니다. 다음 표에는 데이터를 캐시하는 데 사용할 수 있는 Redis 명령어가 나와 있습니다. 앱에서 이러한 명령어를 호출하는 방법은 클라이언트 라이브러리의 문서를 참조하세요.
업데이트 테스트
앱을 로컬에서 테스트할 때는 프로덕션 데이터와의 상호작용을 방지하기 위해 Redis의 로컬 인스턴스를 실행하는 것이 좋습니다(Memorystore는 에뮬레이터를 제공하지 않음). Redis를 로컬에 설치 및 실행하려면 Redis 문서의 안내를 따르세요.
현재 Windows에서는 Redis를 로컬에서 실행할 수 없습니다.
앱 배포
앱이 로컬 개발 서버에서 오류 없이 실행되면 다음을 수행합니다.
App Engine에서 앱을 테스트합니다.
앱이 오류 없이 실행되면 트래픽 분할을 사용하여 업데이트된 앱의 트래픽을 천천히 늘립니다. 앱을 면밀히 모니터링하여 데이터베이스에 문제가 없는 것을 확인한 후 더 많은 트래픽을 업데이트된 앱으로 라우팅합니다.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-09-04(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[[["\u003cp\u003eMemorystore for Redis is recommended for high-performance, scalable web applications that require an in-memory data cache, but it does not have a free tier, so see pricing details.\u003c/p\u003e\n"],["\u003cp\u003eCaching is beneficial for data like session information and user preferences, especially when query results don't need to be immediately reflected in the application, allowing for reduced database queries.\u003c/p\u003e\n"],["\u003cp\u003eApplications must use proper credentials to interact with Memorystore, typically the App Engine default service account unless specific conditions are met, such as different project locations or modified service account roles.\u003c/p\u003e\n"],["\u003cp\u003eTo use Memorystore, you must set up a Redis instance and Serverless VPC Access, install a Redis client library like redigo, configure environment variables for Redis IP and port, and then deploy the app to App Engine.\u003c/p\u003e\n"],["\u003cp\u003eRedis commands like SET, GET, INCR, and DEL are essential for managing cached data, including creating, retrieving, incrementing, and deleting entries, with concurrent interactions supported through Redis transactions.\u003c/p\u003e\n"]]],[],null,["# Caching data with Memorystore\n\nHigh performance scalable web applications often use a distributed in-memory data cache in front of or in place of robust persistent storage for some tasks. We recommend using Memorystore for Redis as your caching service. Note that **Memorystore for Redis does not provide a free tier** . See [Memorystore Pricing](/memorystore/pricing) for details.\n\n\u003cbr /\u003e\n\nBefore getting started, make sure your app will stay within the\n[Memorystore for Redis quotas](/memorystore/docs/redis/quotas).\n\nWhen to use a memory cache\n--------------------------\n\nSession data, user preferences, and other data returned by queries for web pages\nare good candidates for caching. In general, if a frequently run query returns\na set of results that do not need to appear in your app immediately, you can\ncache the results. Subsequent requests can check the cache and only query the\ndatabase if the results are absent or have expired.\n\nIf you store a value only in Memorystore without backing it up in\npersistent storage, be sure that your application behaves acceptably if the\nvalue expires and is removed from the cache. For example, if the sudden absence\nof a user's session data would cause the session to malfunction, that data\nshould probably be stored in the database in addition to Memorystore.\n\n\nUnderstanding Memorystore permissions\n-------------------------------------\n\nEvery interaction with a Google Cloud service needs to be authorized. For\nexample, to interact with a Redis database hosted by Memorystore, your app\nneeds to supply the credentials of an account that is authorized to access\nMemorystore.\n\nBy default your app supplies the credentials of the App Engine\ndefault [service account](/iam/docs/service-accounts), which is authorized to\naccess databases in the same project as your app.\n\nIf any of the following conditions are true, you need to use an alternative\nauthentication technique that explicitly provides credentials:\n\n- Your app and the Memorystore database are in different\n Google Cloud projects.\n\n- You have changed the roles assigned to the default App Engine\n service account.\n\nFor information about alternative authentication techniques, see\n[Setting up Authentication for Server to Server Production\nApplications](/docs/authentication/production#auth-cloud-implicit-python).\n\nOverview of using Memorystore\n-----------------------------\n\nTo use Memorystore in your app:\n\n\n1. [Set up Memorystore for Redis](#setup_redis_db), which requires you\n to create a Redis instance on Memorystore and create a\n Serverless VPC Access that your app uses to communicate with the\n Redis instance. The order of creating these two independent entities is not\n strict and can be set up in any order. The instructions in this guide show\n setting up Serverless VPC Access first.\n\n2. Install a client library for Redis and use Redis commands to cache data.\n\n Memorystore for Redis is compatible with [any client library for\n Redis](https://redis.io/clients).\n\n This guide describes using the\n [redigo](https://github.com/gomodule/redigo)\n client library to send Redis commands from your app.\n3. [Test your updates](#testing).\n\n4. [Deploy your app to App Engine](#deploying).\n\nSetting up Memorystore for Redis\n--------------------------------\n\nTo set up Memorystore for Redis:\n\n1. [Connect your App Engine to a VPC\n network](/appengine/docs/legacy/standard/go111/connecting-vpc). Your app\n can only communicate with Memorystore through a VPC connector.\n\n Be sure to add the VPC connection information to your `app.yaml` file as\n described in [Configuring your app use the\n connector](/appengine/docs/standard/connecting-vpc#configuring).\n2. Note the IP address and port number of the Redis instance you create.\n You will use this information when you [create a Redis client](#redis_client)\n in your code.\n\n3. [Create a Redis instance](/memorystore/docs/redis/creating-managing-instances#creating_a_redis_instance_on_a_vpc_network)\n in Memorystore.\n\n When prompted to select a region for your Redis instance, select the\n [same region\n in which your App Engine app is located](/appengine/docs/legacy/standard/go111/locations).\n\nInstalling dependencies\n-----------------------\n\nTo make the redigo client library available to your app when it runs in App Engine, add the library to your app's dependencies. For example, if you use a `go.mod` file to declare dependencies, add the following line to your `go.mod` file:\n\n\u003cbr /\u003e\n\n module github.com/GoogleCloudPlatform/golang-samples/tree/master/memorystore/redis\n\nLearn more about [specifying dependencies](/appengine/docs/legacy/standard/go111/specifying-dependencies)\nfor your Go app.\n\nCreating a Redis client\n-----------------------\n\nTo interact with a Redis database, your code needs to create a Redis client to\nmanage the connection to your Redis database. The following sections describe\ncreating a Redis client using the\n\nredigo\n\nclient library.\n\n### Specifying environment variables\n\nThe\n\nredigo\n\nclient library uses two environment variables\nto assemble the URL for your Redis database:\n\n- A variable to identify the IP address of the Redis database you [created in Memorystore](#setup_redis_db).\n- A variable to identify the port number of the Redis database you created in Memorystore.\n\nWe recommend you define these variables in your app's `app.yaml` file instead of\ndefining them directly in your code. This makes it easier to run your app in\ndifferent environments, such as a local environment and App Engine.\nFor example, add the following lines to your `app.yaml` file:\n\n\u003cbr /\u003e\n\n env_variables:\n REDISHOST: '10.112.12.112'\n REDISPORT: '6379'\n\n### Importing\nredigo\nand creating the client\n\nAfter you define the `REDISHOST` and `REDISPORT` environment variables, use the following lines to import the redigo library, create a connection pool, and then retrieve a Redis client from the pool:\n\n\u003cbr /\u003e\n\n\n // Command redis is a basic app that connects to a managed Redis instance.\n package main\n\n import (\n \t\"fmt\"\n \t\"log\"\n \t\"net/http\"\n \t\"os\"\n\n \t\"github.com/gomodule/redigo/redis\"\n )\n\n var redisPool *redis.Pool\n\n func incrementHandler(w http.ResponseWriter, r *http.Request) {\n \tconn := redisPool.Get()\n \tdefer conn.Close()\n\n \tcounter, err := redis.Int(conn.Do(\"INCR\", \"visits\"))\n \tif err != nil {\n \t\thttp.Error(w, \"Error incrementing visitor counter\", http.StatusInternalServerError)\n \t\treturn\n \t}\n \tfmt.Fprintf(w, \"Visitor number: %d\", counter)\n }\n\n func main() {\n \tredisHost := os.Getenv(\"REDISHOST\")\n \tredisPort := os.Getenv(\"REDISPORT\")\n \tredisAddr := fmt.Sprintf(\"%s:%s\", redisHost, redisPort)\n\n \tconst maxConnections = 10\n \tredisPool = &redis.Pool{\n \t\tMaxIdle: maxConnections,\n \t\tDial: func() (redis.Conn, error) { return redis.Dial(\"tcp\", redisAddr) },\n \t}\n\n \thttp.HandleFunc(\"/\", incrementHandler)\n\n \tport := os.Getenv(\"PORT\")\n \tif port == \"\" {\n \t\tport = \"8080\"\n \t}\n \tlog.Printf(\"Listening on port %s\", port)\n \tif err := http.ListenAndServe(\":\"+port, nil); err != nil {\n \t\tlog.Fatal(err)\n \t}\n }\n\nUsing Redis commands to store and retrieve data in the cache\n------------------------------------------------------------\n\nWhile the Memorystore Redis database [supports most\nRedis commands](/memorystore/docs/redis/product-constraints), you only need to use a few commands to\nstore and retrieve data from the cache. The following table suggests Redis\ncommands you can use to cache data. To see how to call these commands from your\napp, view your client library's documentation.\n\nTesting your updates\n--------------------\n\nWhen you test your app locally, consider running a local instance of\nRedis to avoid interacting with production data (Memorystore doesn't\nprovide an emulator). To install and run Redis locally, follow the directions in the\n[Redis documentation](http://redis.io/topics/quickstart).\nNote that it currently isn't possible to run Redis locally on Windows.\n\nDeploying your app\n------------------\n\nOnce your app is running in the local development server without errors:\n\n1.\n [Test the app on\n App Engine](/appengine/docs/legacy/standard/go111/testing-and-deploying-your-app#testing-on-app-engine).\n\n2. If the app runs without errors, [use traffic\n splitting](/appengine/docs/legacy/standard/go111/splitting-traffic) to slowly\n ramp up traffic for your updated app. Monitor the app closely for any\n database issues before routing more traffic to the updated app."]]