下面列出了怎么用io.grpc.ManagedChannelBuilder的API类实例代码及写法,或者点击链接到github查看源代码。
@BeforeClass(enabled = true)
public void beforeClass() {
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
ByteString addressBs1 = ByteString.copyFrom(fromAddress);
Account request1 = Account.newBuilder().setAddress(addressBs1).build();
GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull
.getAssetIssueByAccount(request1);
Optional<GrpcAPI.AssetIssueList> queryAssetByAccount = Optional.ofNullable(assetIssueList1);
if (queryAssetByAccount.get().getAssetIssueCount() == 0) {
Long start = System.currentTimeMillis() + 2000;
Long end = System.currentTimeMillis() + 1000000000;
//Create a new asset issue
Assert.assertTrue(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 6, 1000,
start, end, 2, description, url, 10000L, 10000L,
1L, 1L, testKey002, blockingStubFull));
PublicMethed.waitProduceNextBlock(blockingStubFull);
} else {
logger.info("This account already create an assetisue");
}
}
/**
* constructor.
*/
@BeforeClass(enabled = true)
public void beforeClass() {
PublicMethed.printAddress(contractExcKey);
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
channelFull1 = ManagedChannelBuilder.forTarget(fullnode1)
.usePlaintext(true)
.build();
blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1);
channelConfirmed = ManagedChannelBuilder.forTarget(confirmednode)
.usePlaintext(true)
.build();
blockingStubConfirmed = WalletConfirmedGrpc.newBlockingStub(channelConfirmed);
}
void run() throws Exception {
// Port 0 means that the operating system will pick an available port to use.
Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
responseObserver.onError(Status.INTERNAL
.withDescription("Eggplant Xerxes Crybaby Overbite Narwhal").asRuntimeException());
}
}).build().start();
channel =
ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext().build();
blockingCall();
futureCallDirect();
futureCallCallback();
asyncCall();
advancedAsyncCall();
channel.shutdown();
server.shutdown();
channel.awaitTermination(1, TimeUnit.SECONDS);
server.awaitTermination();
}
@Test
void uncompressedClient_compressedEndpoint() throws Exception {
final ManagedChannel nonDecompressingChannel =
ManagedChannelBuilder.forAddress("127.0.0.1", server.httpPort())
.decompressorRegistry(
DecompressorRegistry.emptyInstance()
.with(Codec.Identity.NONE, false))
.usePlaintext()
.build();
final UnitTestServiceBlockingStub client = UnitTestServiceGrpc.newBlockingStub(
nonDecompressingChannel);
assertThat(client.staticUnaryCallSetsMessageCompression(REQUEST_MESSAGE))
.isEqualTo(RESPONSE_MESSAGE);
nonDecompressingChannel.shutdownNow();
checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
assertThat(rpcReq.method()).isEqualTo(
"armeria.grpc.testing.UnitTestService/StaticUnaryCallSetsMessageCompression");
assertThat(rpcReq.params()).containsExactly(REQUEST_MESSAGE);
assertThat(rpcRes.get()).isEqualTo(RESPONSE_MESSAGE);
});
}
@Before
public void initializeChannel() throws IOException {
grpcCleanup.register(serverBuilder.build().start());
channel = grpcCleanup.register(channelBuilder.maxInboundMessageSize(1024).build());
client2Channel =
grpcCleanup.register(client2ChannelBuilder.maxInboundMessageSize(1024).build());
if (app.getAuthServerHost() != null && app.getAuthServerPort() != null) {
authServiceChannelClient1 =
ManagedChannelBuilder.forTarget(app.getAuthServerHost() + ":" + app.getAuthServerPort())
.usePlaintext()
.intercept(authClientInterceptor.getClient1AuthInterceptor())
.build();
authServiceChannelClient2 =
ManagedChannelBuilder.forTarget(app.getAuthServerHost() + ":" + app.getAuthServerPort())
.usePlaintext()
.intercept(authClientInterceptor.getClient2AuthInterceptor())
.build();
}
}
/**
* constructor.
*/
@BeforeClass(enabled = true)
public void beforeClass() {
PublicMethed.printAddress(contractExcKey);
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
channelFull1 = ManagedChannelBuilder.forTarget(fullnode1)
.usePlaintext(true)
.build();
blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1);
channelConfirmed = ManagedChannelBuilder.forTarget(confirmednode)
.usePlaintext(true)
.build();
blockingStubConfirmed = WalletConfirmedGrpc.newBlockingStub(channelConfirmed);
}
@Inject
public ReviewCommand(
FileUtils utils,
Config config,
GitRepoFactory repoFactory,
@Named("Workspace path") String workspacePath,
@Named("Diff number") Integer diffNumber) {
this.fileUtils = utils;
this.gitRepoFactory = repoFactory;
this.workspacePath = workspacePath;
this.diffNumber = diffNumber;
ManagedChannel channel =
ManagedChannelBuilder.forAddress("localhost", GRPC_PORT).usePlaintext().build();
codeReviewBlockingStub = CodeReviewServiceGrpc.newBlockingStub(channel);
}
public boolean renewLock(String sessionId) throws Exception {
UcoreInterface.RenewSessionInput input = UcoreInterface.RenewSessionInput.newBuilder().setSessionId(sessionId).build();
try {
stub.withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS).renewSession(input);
return true;
} catch (Exception e1) {
LOGGER.info("connect to ucore renew error and will retry");
for (String ip : getIpList()) {
ManagedChannel channel = null;
try {
channel = ManagedChannelBuilder.forAddress(ip,
Integer.parseInt(getValue(ClusterParamCfg.CLUSTER_PLUGINS_PORT))).usePlaintext(true).build();
stub = UcoreGrpc.newBlockingStub(channel).withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS);
stub.withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS).renewSession(input);
return true;
} catch (Exception e2) {
LOGGER.info("connect to ucore renew error " + stub, e2);
if (channel != null) {
channel.shutdownNow();
}
}
}
return false;
}
}
/**
* constructor.
*/
@BeforeClass(enabled = true)
public void beforeClass() {
PublicMethed.printAddress(contractExcKey);
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
channelFull1 = ManagedChannelBuilder.forTarget(fullnode1)
.usePlaintext(true)
.build();
blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1);
channelConfirmed = ManagedChannelBuilder.forTarget(confirmednode)
.usePlaintext(true)
.build();
blockingStubConfirmed = WalletConfirmedGrpc.newBlockingStub(channelConfirmed);
}
/**
* constructor.
*/
@BeforeClass(enabled = true)
public void beforeClass() {
PublicMethed.printAddress(contract003Key);
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
logger.info(Long.toString(PublicMethed.queryAccount(contract003Key, blockingStubFull)
.getBalance()));
channelFull1 = ManagedChannelBuilder.forTarget(fullnode1)
.usePlaintext(true)
.build();
blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1);
}
protected final void connectToPeer() throws IOException {
// The ChaincodeSupport Client is a wrapper around the gRPC streams that
// come from the single 'register' call that is made back to the peer
//
// Once this has been created, the InvocationTaskManager that is responsible
// for the thread management can be created.
//
// This is then passed to the ChaincodeSupportClient to be connected to the
// gRPC streams
final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName(this.id).build();
final ManagedChannelBuilder<?> channelBuilder = newChannelBuilder();
final ChaincodeSupportClient chaincodeSupportClient = new ChaincodeSupportClient(channelBuilder);
final InvocationTaskManager itm = InvocationTaskManager.getManager(this, chaincodeId);
chaincodeSupportClient.start(itm);
}
/**
* constructor.
*/
@BeforeClass(enabled = true)
public void beforeClass() {
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
PublicMethed.printAddress(dev001Key);
PublicMethed.printAddress(user001Key);
String fakeAddress = "";
logger.info("realAddress: " + fakeAddress);
byte[] fullHexAddr = new DataWord(fakeAddress).getData();
logger.info("fullHexAddr ++= " + Hex.toHexString(fullHexAddr));
fakeAddress = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
logger.info("realAddress: " + fakeAddress);
fullHexAddr = new DataWord(fakeAddress).getData();
logger.info("fullHexAddr ++= " + Hex.toHexString(fullHexAddr));
}
public ManagedChannel getChannel(String addressStr) {
return connPool.computeIfAbsent(
addressStr,
key -> {
URI address;
try {
address = URI.create("http://" + key);
} catch (Exception e) {
throw new IllegalArgumentException("failed to form address " + key);
}
// Channel should be lazy without actual connection until first call
// So a coarse grain lock is ok here
return ManagedChannelBuilder.forAddress(address.getHost(), address.getPort())
.maxInboundMessageSize(maxFrameSize)
.usePlaintext(true)
.idleTimeout(60, TimeUnit.SECONDS)
.build();
});
}
/**
* constructor.
*/
@BeforeClass(enabled = true)
public void beforeClass() {
PublicMethed.printAddress(contractExcKey);
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
channelFull1 = ManagedChannelBuilder.forTarget(fullnode1)
.usePlaintext(true)
.build();
blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1);
channelConfirmed = ManagedChannelBuilder.forTarget(confirmednode)
.usePlaintext(true)
.build();
blockingStubConfirmed = WalletConfirmedGrpc.newBlockingStub(channelConfirmed);
}
/**
* constructor.
*/
@BeforeClass(enabled = true)
public void beforeClass() {
PublicMethed.printAddress(contractExcKey);
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
channelFull1 = ManagedChannelBuilder.forTarget(fullnode1)
.usePlaintext(true)
.build();
blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1);
channelConfirmed = ManagedChannelBuilder.forTarget(confirmednode)
.usePlaintext(true)
.build();
blockingStubConfirmed = WalletConfirmedGrpc.newBlockingStub(channelConfirmed);
}
/**
* constructor.
*/
@BeforeClass(enabled = true)
public void beforeClass() {
PublicMethed.printAddress(contractExcKey);
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
channelFull1 = ManagedChannelBuilder.forTarget(fullnode1)
.usePlaintext(true)
.build();
blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1);
channelConfirmed = ManagedChannelBuilder.forTarget(confirmednode)
.usePlaintext(true)
.build();
blockingStubConfirmed = WalletConfirmedGrpc.newBlockingStub(channelConfirmed);
}
@Before
public void setupServer() throws Exception {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(3));
server = ServerBuilder
.forPort(0)
.addService(service)
.executor(Executors.newSingleThreadExecutor(
new ThreadFactoryBuilder().setNameFormat("TheGrpcServer").build()))
.build()
.start();
channel = ManagedChannelBuilder
.forAddress("localhost", server.getPort())
.usePlaintext()
.executor(Executors.newSingleThreadExecutor(
new ThreadFactoryBuilder().setNameFormat("TheGrpcClient").build()))
.build();
}
@Test
public void consumer() {
ManagedChannel syncRequestChannel = null;
try {
syncRequestChannel = ManagedChannelBuilder.forAddress("localhost", consumerPort).usePlaintext().build();
final PingPongBlockingStub blockingStub = PingPongGrpc.newBlockingStub(syncRequestChannel);
final PingRequest pingRequest = PingRequest.newBuilder()
.setPingName("foo")
.setPingId(567)
.build();
final PongResponse pongResponse = blockingStub.pingSyncSync(pingRequest);
Assertions.assertNotNull(pongResponse);
Assertions.assertEquals(567, pongResponse.getPongId());
Assertions.assertEquals("foo PONG", pongResponse.getPongName());
} finally {
if (syncRequestChannel != null) {
syncRequestChannel.shutdownNow();
}
}
}
@Test
public void remoteSampling_perOperation() {
Assume.assumeNotNull(jaegerContainer);
String jaegerHost =
String.format("127.0.0.1:%d", jaegerContainer.getMappedPort(COLLECTOR_PORT));
final JaegerRemoteSampler remoteSampler =
JaegerRemoteSampler.newBuilder()
.setChannel(ManagedChannelBuilder.forTarget(jaegerHost).usePlaintext().build())
.setServiceName(SERVICE_NAME)
.build();
Awaitility.await()
.atMost(10, TimeUnit.SECONDS)
.until(samplerIsType(remoteSampler, PerOperationSampler.class));
Assert.assertTrue(remoteSampler.getSampler() instanceof PerOperationSampler);
Assert.assertTrue(remoteSampler.getDescription().contains("0.33"));
Assert.assertFalse(remoteSampler.getDescription().contains("150"));
}
/**
* Construct client for accessing GreeterGrpc server.
*/
AuthClient(CallCredentials callCredentials, String host, int port) {
this(
callCredentials,
ManagedChannelBuilder
.forAddress(host, port)
// Channels are secure by default (via SSL/TLS). For this example we disable TLS
// to avoid needing certificates, but it is recommended to use a secure channel
// while passing credentials.
.usePlaintext()
.build());
}
/**
* Method for setting up a channel.
*
* @param ipAddress ipAddress of the socket.
* @throws Exception exception while setting up.
*/
private void setupChannel(final InetSocketAddress ipAddress) throws Exception {
this.managedChannel = ManagedChannelBuilder.forAddress(ipAddress.getHostName(), ipAddress.getPort())
.usePlaintext()
.build();
this.blockingStub = MessageServiceGrpc.newBlockingStub(managedChannel);
this.asyncStub = MessageServiceGrpc.newStub(managedChannel);
}
/**
* constructor.
*/
@BeforeClass(enabled = true)
public void beforeClass() {
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
}
/**
* constructor.
*/
@BeforeClass(enabled = true)
public void beforeClass() {
PublicMethed.printAddress(contract013Key);
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
}
/** Construct client connecting to HelloWorld server at {@code host:port}. */
public HelloWorldClient(String host, int port) {
this(ManagedChannelBuilder.forAddress(host, port)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext()
.build());
}
@Test
public void triggerContract2() {
String priKey = "374f8288a296d5267bc8157b2eead62fb7a882bfbd2fa132bebe0dd5e9332925";
BigInteger key = new BigInteger(priKey, 16);
ECKey ecKey = ECKey.fromPrivate(key);
byte[] address = ecKey.getAddress();
// String node = "39.105.135.130:5021";
String node = "47.74.14.144:5021";
ManagedChannel channel = null;
WalletGrpc.WalletBlockingStub blockingStubFull = null;
channel = ManagedChannelBuilder.forTarget(node).usePlaintext(true).build();
blockingStubFull = WalletGrpc.newBlockingStub(channel);
byte[] contractAddress = Hex.decode("01f80c992fb573850cd88e7cc80cde58dcaf1afb1e9dde");
Protocol.SmartContract smartContract = blockingStubFull.getContract(GrpcAPI.BytesMessage.newBuilder().setValue(ByteString.copyFrom(contractAddress)).build());
// System.out.println("Smart contract: " + smartContract.toString());
String method = "slotting(uint256,uint256,bool)";
String argsStr = "20000000,90,true";
Boolean isHex = false;
long callValue = 20000000L;
long feeLimit = 100000000L;
byte[] ownerAddress = address;
String tokenId = "0";
long tokenValue = 0;
String trxId = PublicMethed.triggerContract(contractAddress, method, argsStr, isHex, callValue, feeLimit, tokenId, tokenValue, ownerAddress, priKey, blockingStubFull);
System.out.println(trxId);
}
/**
* constructor.
*/
@BeforeClass(enabled = false)
public void beforeClass() {
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
}
/**
* constructor.
*/
@BeforeClass
public void beforeClass() {
PublicMethed.printAddress(lowBalTest);
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
}
public void testGrpc() {
WalletBlockingStub walletStub = WalletGrpc
.newBlockingStub(ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build());
logger.info("getNodeInfo: {}", walletStub.getNodeInfo(EmptyMessage.getDefaultInstance()));
}
/**
* Creates Managed Channel wrapper from endpoint address
*
* @return the wrapper object
*/
private ManagedChannelWrapper makeWrapper() {
return new ManagedChannelWrapper(
ManagedChannelBuilder.forAddress(auditConfig.getHost(), auditConfig.getPort())
.usePlaintext()
.maxInboundMessageSize(DEFAULT_MAX_MESSAGE_SIZE)
.build());
}
/**
* constructor.
*/
@BeforeClass(enabled = true)
public void beforeClass() {
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext(true)
.build();
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
}