Created
July 9, 2022 10:44
-
-
Save tsonglew/4f295d4396651e4060c4a6e115c0fbfc to your computer and use it in GitHub Desktop.
some base retryable grpc client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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