Search code examples
google-app-engineredisgoogle-cloud-platformgoogle-cloud-memorystore

How to access memorystore from App engine standard environment?


We deploy our app on Google app engine standard environment. We need to access Memorystore(redis) from our app engine.

Following the document, we create Serverless VPC access connector and configure the app engine:

<vpc-access-connector>
  <name>projects/PROJECT_ID/locations/REGION/connectors/CONNECTOR_NAME</name>
</vpc-access-connector>

and set the IAM permissions. But we still can not connect to redis instance at private IP like 10.0.0.4 using jedis:

Jedis jedis = new Jedis("10.0.0.4");


Solution

  • It should work if you deploy it with gcloud beta app deploy target/SNAPSHOT.

    I prepared and uploaded a sample in Github.

    How I did it in a new project:

    1. Enabled App Engine, selected region us-central (corresponds to us-central1)
    2. Created Memorystore instance, in region us-central1
    3. Created VPC Connector, in region us-central1 (At the moment no other region can be selected, so both App Engine and Memorystore have to be in us-central1)
    4. Added the VPC connector in appengine-web.xml:
    <vpc-access-connector>
      <name>projects/PROJECT_ID/locations/us-central1/connectors/CONNECTOR_NAME</name>
    </vpc-access-connector>
    
    1. Modified pom.xml, adding the following dependency:
        <dependency>
           <groupId>redis.clients</groupId>
           <artifactId>jedis</artifactId>
           <version>3.1.0</version>
           <type>jar</type>
           <scope>compile</scope>
        </dependency>
    
    1. Modified the servlet.java file:
    import java.io.IOException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import redis.clients.jedis.Jedis;
    
    @WebServlet(
        name = "Redis",
        description = "Redis: Connect to Redis",
        urlPatterns = "/redis"
    )
    public class RedisServlet extends HttpServlet {
    
      @Override
      public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            String s;
            try{
                    Jedis jedis = new Jedis("10.0.0.4");
                    jedis.set("myKey", "It's alive");
                    s = "Life test: "+ jedis.get("myKey");
            }catch(Exception e){s = "Couldn't connect "; e.printStackTrace();}
    
           resp.getWriter().write(s);
      }
    }
    
    1. Ran the following to package and deploy:

    mvn package (This will create a "target" folder)

    gcloud beta app deploy target/ARTIFACT_ID-1.0-SNAPSHOT
    

    Note that it's still in BETA and it might not work very reliably.