Skip to content

Instantly share code, notes, and snippets.

@tsonglew
Created July 9, 2022 10:44
Show Gist options
  • Save tsonglew/4f295d4396651e4060c4a6e115c0fbfc to your computer and use it in GitHub Desktop.
Save tsonglew/4f295d4396651e4060c4a6e115c0fbfc to your computer and use it in GitHub Desktop.
some base retryable grpc client
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
// grpc_config.json
{
"methodConfig": [
{
"name": [
{ "service": "com.module.Service" }
],
"timeout": "50s",
"retryPolicy": {
"maxAttempts" : 15,
"initialBackoff" : "1s",
"maxBackoff": "30s",
"backoffMultiplier": 30,
"retryableStatusCodes": [ "UNAVAILABLE" ]
}
}
]
}
*/
public interface BaseGrpcClient {
/**
* get retry config
* @return {@link Map}
* @throws IOException {@link IOException} some exception
*/
default Map<String, ?> getRetryingServiceConfig() throws IOException {
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource("grpc_config.json");
return new Gson()
.fromJson(
new JsonReader(new InputStreamReader(resource.getInputStream(), UTF_8)),
Map.class
);
}
/**
* build a channel
* @param host {@link String}
* @param port {@link Integer}
* @return {@link ManagedChannel}
*/
default ManagedChannel buildChannel(String host, Integer port) {
var channelBuilder = ManagedChannelBuilder.forAddress(host, port).usePlaintext();
try {
channelBuilder.defaultServiceConfig(getRetryingServiceConfig()).enableRetry();
} catch (Exception e){
e.printStackTrace();
}
return channelBuilder.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment