Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dualstack example #11451

Merged
merged 7 commits into from
Aug 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions examples/example-dualstack/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# gRPC Dualstack Example

The dualstack example uses a custom name resolver that provides both IPv4 and IPv6 localhost
endpoints for each of 3 server instances. The client will first use the default name resolver and
load balancers which will only connect tot he first server. It will then use the
custom name resolver with round robin to connect to each of the servers in turn. The 3 instances
of the server will bind respectively to: both IPv4 and IPv6, IPv4 only, and IPv6 only.

The example requires grpc-java to already be built. You are strongly encouraged
to check out a git release tag, since there will already be a build of grpc
available. Otherwise, you must follow [COMPILING](../../COMPILING.md).

### Build the example

To build the dualstack example server and client. From the
`grpc-java/examples/example-dualstack` directory run:

```bash
$ ../gradlew installDist
```

This creates the scripts
`build/install/example-dualstack/bin/dual-stack-server`
and `build/install/example-dualstack/bin/dual-stack-client`.

To run the dualstack example, run the server with:

```bash
$ ./build/install/example-dualstack/bin/dual-stack-server
```

And in a different terminal window run the client.

```bash
$ ./build/install/example-dualstack/bin/dual-stack-client
```

### Maven

If you prefer to use Maven:

Run in the example-debug directory:

```bash
$ mvn verify
$ # Run the server in one terminal
$ mvn exec:java -Dexec.mainClass=io.grpc.examples.dualstack.DualStackServer
```

```bash
$ # In another terminal run the client
$ mvn exec:java -Dexec.mainClass=io.grpc.examples.dualstack.DualStackClient
```

79 changes: 79 additions & 0 deletions examples/example-dualstack/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
plugins {
id 'application' // Provide convenience executables for trying out the examples.
id 'java'

id "com.google.protobuf" version "0.9.4"

// Generate IntelliJ IDEA's .idea & .iml project files
id 'idea'
}

repositories {
maven { // The google mirror is less flaky than mavenCentral()
url "https://maven-central.storage-download.googleapis.com/maven2/" }
mavenCentral()
mavenLocal()
}

java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}

// IMPORTANT: You probably want the non-SNAPSHOT version of gRPC. Make sure you
// are looking at a tagged version of the example and not "master"!

// Feel free to delete the comment at the next line. It is just for safely
// updating the version in our release process.
def grpcVersion = '1.67.0-SNAPSHOT' // CURRENT_GRPC_VERSION
def protobufVersion = '3.25.3'

dependencies {
implementation "io.grpc:grpc-protobuf:${grpcVersion}"
implementation "io.grpc:grpc-netty:${grpcVersion}"
implementation "io.grpc:grpc-stub:${grpcVersion}"
implementation "io.grpc:grpc-services:${grpcVersion}"
compileOnly "org.apache.tomcat:annotations-api:6.0.53"
}

protobuf {
protoc {
artifact = "com.google.protobuf:protoc:${protobufVersion}"
}
plugins {
grpc {
artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}"
}
}
generateProtoTasks {
all()*.plugins {
grpc {}
}
}
}

startScripts.enabled = false

task DualStackClient(type: CreateStartScripts) {
mainClass = 'io.grpc.examples.dualstack.DualStackClient'
applicationName = 'dual-stack-client'
outputDir = new File(project.buildDir, 'tmp/scripts/' + name)
classpath = startScripts.classpath
}

task DualStackServer(type: CreateStartScripts) {
mainClass = 'io.grpc.examples.dualstack.DualStackServer'
applicationName = 'dual-stack-server'
outputDir = new File(project.buildDir, 'tmp/scripts/' + name)
classpath = startScripts.classpath
}

application {
applicationDistribution.into('bin') {
from(DualStackClient)
from(DualStackServer)
filePermissions {
unix(0755)
}
}
}
122 changes: 122 additions & 0 deletions examples/example-dualstack/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.grpc</groupId>
<artifactId>example-dualstack</artifactId>
<packaging>jar</packaging>
<!-- Feel free to delete the comment at the end of these lines. It is just
for safely updating the version in our release process. -->
<version>1.67.0-SNAPSHOT</version><!-- CURRENT_GRPC_VERSION -->
<name>example-dualstack</name>
<url>https://github.com/grpc/grpc-java</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<grpc.version>1.67.0-SNAPSHOT</grpc.version><!-- CURRENT_GRPC_VERSION -->
<protoc.version>3.25.3</protoc.version>
<!-- required for jdk9 -->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-bom</artifactId>
<version>${grpc.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-services</artifactId>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>annotations-api</artifactId>
<version>6.0.53</version>
<scope>provided</scope> <!-- not needed at runtime -->
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-testing</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.7.1</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version>
<executions>
<execution>
<id>enforce</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireUpperBoundDeps/>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
10 changes: 10 additions & 0 deletions examples/example-dualstack/settings.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
pluginManagement {
repositories {
maven { // The google mirror is less flaky than mavenCentral()
url "https://maven-central.storage-download.googleapis.com/maven2/"
}
gradlePluginPortal()
}
}

rootProject.name = 'example-dualstack'
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* Copyright 2024 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.grpc.examples.dualstack;

import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.NameResolverRegistry;
import io.grpc.StatusRuntimeException;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* A client that requests greetings from the {@link DualStackServer}.
* First it sends 5 requests using the default nameresolver and load balancer.
* Then it sends 10 requests using the example nameresolver and round robin load balancer. These
* requests are evenly distributed among the 3 servers rather than favoring the server listening
* on both addresses because the ExampleDualStackNameResolver groups the 3 servers as 3 endpoints
* each with 2 addresses.
*/
public class DualStackClient {
larry-safran marked this conversation as resolved.
Show resolved Hide resolved
public static final String channelTarget = "example:///lb.example.grpc.io";
private static final Logger logger = Logger.getLogger(DualStackClient.class.getName());
private final GreeterGrpc.GreeterBlockingStub blockingStub;

public DualStackClient(Channel channel) {
blockingStub = GreeterGrpc.newBlockingStub(channel);
}

public static void main(String[] args) throws Exception {
NameResolverRegistry.getDefaultRegistry()
.register(new ExampleDualStackNameResolverProvider());

logger.info("\n **** Use default DNS resolver ****");
ManagedChannel channel = ManagedChannelBuilder.forTarget("localhost:50051")
.usePlaintext()
.build();
try {
DualStackClient client = new DualStackClient(channel);
for (int i = 0; i < 5; i++) {
client.greet("request:" + i);
}
} finally {
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}

logger.info("\n **** Change to use example name resolver ****");
/*
Dial to "example:///resolver.example.grpc.io", use {@link ExampleNameResolver} to create connection
"resolver.example.grpc.io" is converted to {@link java.net.URI.path}
*/
channel = ManagedChannelBuilder.forTarget(channelTarget)
.defaultLoadBalancingPolicy("round_robin")
.usePlaintext()
.build();
try {
DualStackClient client = new DualStackClient(channel);
for (int i = 0; i < 10; i++) {
client.greet("request:" + i);
}
} finally {
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}
}

public void greet(String name) {
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloReply response;
try {
response = blockingStub.sayHello(request);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
logger.info("Greeting: " + response.getMessage());
}
}
Loading
Loading