本文整理汇总了Java中io.grpc.Attributes类的典型用法代码示例。如果您正苦于以下问题:Java Attributes类的具体用法?Java Attributes怎么用?Java Attributes使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Attributes类属于io.grpc包,在下文中一共展示了Attributes类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: startServer
import io.grpc.Attributes; //导入依赖的package包/类
@BeforeClass
public static void startServer() throws IOException {
AfricasTalking.initialize(Fixtures.USERNAME, Fixtures.API_KEY);
server = new Server(new Authenticator() {
@Override
public boolean authenticate(String client) {
return client.compareToIgnoreCase(TEST_CLIENT_ID) == 0;
}
});
server.addSipCredentials("test", "secret", "sip://at.dev");
server.start(certFile, privateKeyFile, TEST_PORT);
ManagedChannel ch = NettyChannelBuilder.forAddress("localhost", TEST_PORT)
.sslContext(GrpcSslContexts.forClient().trustManager(certFile).build())
.build();
client = SdkServerServiceGrpc.newBlockingStub(ch)
.withCallCredentials(new CallCredentials(){
@Override
public void applyRequestMetadata(MethodDescriptor<?, ?> method, Attributes attrs, Executor appExecutor,
final MetadataApplier applier) {
appExecutor.execute(new Runnable(){
@Override
public void run() {
try {
Metadata headers = new Metadata();
Metadata.Key<String> clientIdKey = Metadata.Key.of("X-Client-Id", Metadata.ASCII_STRING_MARSHALLER);
headers.put(clientIdKey, TEST_CLIENT_ID);
applier.apply(headers);
} catch(Throwable ex) {
applier.fail(Status.UNAUTHENTICATED.withCause(ex));
}
}
});
}
});
}
示例2: notifyLoadBalance
import io.grpc.Attributes; //导入依赖的package包/类
/**** help method *****/
private void notifyLoadBalance(GrpcURL subscribeUrl, List<GrpcURL> urls) {
if (urls != null && !urls.isEmpty()) {
List<EquivalentAddressGroup> servers = Lists.newArrayList();
List<SocketAddress> addresses = Lists.newArrayList();
Map<List<SocketAddress>, GrpcURL> addressUrlMapping = Maps.newHashMap();
for (GrpcURL url : urls) {
String host = url.getHost();
int port = url.getPort();
List<SocketAddress> hostAddressMapping;
if (NetUtils.isIP(host)) {
hostAddressMapping = IpResolved(servers, addresses, host, port);
} else {
hostAddressMapping = DnsResolved(servers, addresses, host, port);
}
addressUrlMapping.put(hostAddressMapping, url);
}
this.addresses.put(subscribeUrl, addresses);
Attributes config = this.buildAttributes(subscribeUrl, addressUrlMapping);
GrpcNameResolver.this.listener.onAddresses(servers, config);
} else {
GrpcNameResolver.this.listener
.onError(Status.NOT_FOUND.withDescription("There is no service registy in consul "));
}
}
示例3: update
import io.grpc.Attributes; //导入依赖的package包/类
private void update(Endpoints endpoints) {
List<EquivalentAddressGroup> servers = new ArrayList<>();
endpoints.getSubsets().stream().forEach(subset -> {
long matchingPorts = subset.getPorts().stream().filter(p -> {
return p.getPort() == port;
}).count();
if (matchingPorts > 0) {
subset.getAddresses().stream().map(address -> {
return new EquivalentAddressGroup(new InetSocketAddress(address.getIp(), port));
}).forEach(address -> {
servers.add(address);
});
}
});
listener.onAddresses(servers, Attributes.EMPTY);
}
示例4: start
import io.grpc.Attributes; //导入依赖的package包/类
@Override
@Synchronized
public void start(Listener listener) {
Preconditions.checkState(this.resolverUpdater == null, "ControllerNameResolver has already been started");
Preconditions.checkState(!shutdown, "ControllerNameResolver is shutdown, restart is not supported");
this.resolverUpdater = listener;
// If the servers comprise only of IP addresses then we need to update the controller list only once.
if (this.scheduledExecutor == null) {
// Use the bootstrapped server list as the final set of controllers.
List<EquivalentAddressGroup> servers = this.bootstrapServers.stream()
.map(address -> new EquivalentAddressGroup(
new InetSocketAddress(address.getHostString(), address.getPort())))
.collect(Collectors.toList());
log.info("Updating client with controllers: {}", servers);
this.resolverUpdater.onAddresses(servers, Attributes.EMPTY);
return;
}
// Schedule the first discovery immediately.
this.scheduledFuture = this.scheduledExecutor.schedule(this::getControllers, 0L, TimeUnit.SECONDS);
}
示例5: newNameResolver
import io.grpc.Attributes; //导入依赖的package包/类
@Nullable
@Override
public NameResolver newNameResolver(URI targetUri, Attributes params) {
if (SCHEME.equals(targetUri.getScheme())) {
String targetPath = Preconditions.checkNotNull(targetUri.getPath(), "targetPath");
Preconditions.checkArgument(targetPath.startsWith("/"),
"the path component (%s) of the target (%s) must start with '/'", targetPath, targetUri);
String[] parts = targetPath.split("/");
if (parts.length != 4) {
throw new IllegalArgumentException("Must be formatted like kubernetes:///{namespace}/{service}/{port}");
}
try {
int port = Integer.valueOf(parts[3]);
return new KubernetesNameResolver(parts[1], parts[2], port, params, GrpcUtil.TIMER_SERVICE,
GrpcUtil.SHARED_CHANNEL_EXECUTOR);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Unable to parse port number", e);
}
} else {
return null;
}
}
示例6: newNameResolver
import io.grpc.Attributes; //导入依赖的package包/类
@Nullable
@Override
public NameResolver newNameResolver(URI targetUri, Attributes params) {
final String scheme = targetUri.getScheme();
if (!SCHEME_DISCOVER.equals(scheme) && !SCHEME_DIRECT.equals(scheme)) {
return null;
}
final String authority = targetUri.getAuthority();
final List<InetSocketAddress> addresses = Splitter.on(',').splitToList(authority).stream().map(host -> {
final String[] strings = host.split(":");
Preconditions.checkArgument(strings.length == 2, "URI should have both address and port");
return InetSocketAddress.createUnresolved(strings[0], Integer.valueOf(strings[1]));
}).collect(Collectors.toList());
return new ControllerNameResolver(authority, addresses, SCHEME_DISCOVER.equals(scheme));
}
示例7: serverTracingSampledToLocalSpanStore
import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void serverTracingSampledToLocalSpanStore() {
ServerStreamTracer.Factory tracerFactory = censusTracing.getServerTracerFactory();
ServerStreamTracer serverStreamTracer =
tracerFactory.newServerStreamTracer(sampledMethod.getFullMethodName(), new Metadata());
serverStreamTracer.filterContext(Context.ROOT);
serverStreamTracer.serverCallStarted(
new ServerCallInfoImpl<String, String>(sampledMethod, Attributes.EMPTY, null));
serverStreamTracer.streamClosed(Status.CANCELLED);
verify(spyServerSpan).end(
EndSpanOptions.builder()
.setStatus(io.opencensus.trace.Status.CANCELLED)
.setSampleToLocalSpanStore(true)
.build());
}
示例8: delegatingPickFirstThenNameResolutionFails
import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void delegatingPickFirstThenNameResolutionFails() {
List<EquivalentAddressGroup> resolvedServers = createResolvedServerAddresses(false);
Attributes resolutionAttrs = Attributes.newBuilder().set(RESOLUTION_ATTR, "yeah").build();
deliverResolvedAddresses(resolvedServers, resolutionAttrs);
verify(pickFirstBalancerFactory).newLoadBalancer(helper);
verify(pickFirstBalancer).handleResolvedAddressGroups(eq(resolvedServers), eq(resolutionAttrs));
// Then let name resolution fail. The error will be passed directly to the delegate.
Status error = Status.NOT_FOUND.withDescription("www.google.com not found");
deliverNameResolutionError(error);
verify(pickFirstBalancer).handleNameResolutionError(error);
verify(helper, never())
.updateBalancingState(any(ConnectivityState.class), any(SubchannelPicker.class));
verifyNoMoreInteractions(roundRobinBalancerFactory);
verifyNoMoreInteractions(roundRobinBalancer);
}
示例9: delegatingRoundRobinThenNameResolutionFails
import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void delegatingRoundRobinThenNameResolutionFails() {
List<EquivalentAddressGroup> resolvedServers = createResolvedServerAddresses(false, false);
Attributes resolutionAttrs = Attributes.newBuilder()
.set(RESOLUTION_ATTR, "yeah")
.set(GrpclbConstants.ATTR_LB_POLICY, LbPolicy.ROUND_ROBIN)
.build();
deliverResolvedAddresses(resolvedServers, resolutionAttrs);
verify(roundRobinBalancerFactory).newLoadBalancer(helper);
verify(roundRobinBalancer).handleResolvedAddressGroups(resolvedServers, resolutionAttrs);
// Then let name resolution fail. The error will be passed directly to the delegate.
Status error = Status.NOT_FOUND.withDescription("www.google.com not found");
deliverNameResolutionError(error);
verify(roundRobinBalancer).handleNameResolutionError(error);
verify(helper, never())
.updateBalancingState(any(ConnectivityState.class), any(SubchannelPicker.class));
verifyNoMoreInteractions(pickFirstBalancerFactory);
verifyNoMoreInteractions(pickFirstBalancer);
}
示例10: grpclbUpdatedAddresses_avoidsReconnect
import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void grpclbUpdatedAddresses_avoidsReconnect() {
List<EquivalentAddressGroup> grpclbResolutionList =
createResolvedServerAddresses(true, false);
Attributes grpclbResolutionAttrs = Attributes.newBuilder()
.set(GrpclbConstants.ATTR_LB_POLICY, LbPolicy.GRPCLB).build();
deliverResolvedAddresses(grpclbResolutionList, grpclbResolutionAttrs);
assertSame(LbPolicy.GRPCLB, balancer.getLbPolicy());
verify(helper).createOobChannel(addrsEq(grpclbResolutionList.get(0)), eq(lbAuthority(0)));
ManagedChannel oobChannel = fakeOobChannels.poll();
assertEquals(1, lbRequestObservers.size());
List<EquivalentAddressGroup> grpclbResolutionList2 =
createResolvedServerAddresses(true, false, true);
EquivalentAddressGroup combinedEag = new EquivalentAddressGroup(Arrays.asList(
grpclbResolutionList2.get(0).getAddresses().get(0),
grpclbResolutionList2.get(2).getAddresses().get(0)));
deliverResolvedAddresses(grpclbResolutionList2, grpclbResolutionAttrs);
verify(helper).updateOobChannelAddresses(eq(oobChannel), addrsEq(combinedEag));
assertEquals(1, lbRequestObservers.size()); // No additional RPC
}
示例11: grpclbUpdatedAddresses_reconnectOnAuthorityChange
import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void grpclbUpdatedAddresses_reconnectOnAuthorityChange() {
List<EquivalentAddressGroup> grpclbResolutionList =
createResolvedServerAddresses(true, false);
Attributes grpclbResolutionAttrs = Attributes.newBuilder()
.set(GrpclbConstants.ATTR_LB_POLICY, LbPolicy.GRPCLB).build();
deliverResolvedAddresses(grpclbResolutionList, grpclbResolutionAttrs);
assertSame(LbPolicy.GRPCLB, balancer.getLbPolicy());
verify(helper).createOobChannel(addrsEq(grpclbResolutionList.get(0)), eq(lbAuthority(0)));
ManagedChannel oobChannel = fakeOobChannels.poll();
assertEquals(1, lbRequestObservers.size());
final String newAuthority = "some-new-authority";
List<EquivalentAddressGroup> grpclbResolutionList2 =
createResolvedServerAddresses(false);
grpclbResolutionList2.add(new EquivalentAddressGroup(
new FakeSocketAddress("somethingNew"), lbAttributes(newAuthority)));
deliverResolvedAddresses(grpclbResolutionList2, grpclbResolutionAttrs);
assertTrue(oobChannel.isTerminated());
verify(helper).createOobChannel(addrsEq(grpclbResolutionList2.get(1)), eq(newAuthority));
assertEquals(2, lbRequestObservers.size()); // An additional RPC
}
示例12: fail_inline
import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void fail_inline() {
final Status error = Status.FAILED_PRECONDITION.withDescription("channel not secure for creds");
when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
MetadataApplier applier = (MetadataApplier) invocation.getArguments()[3];
applier.fail(error);
return null;
}
}).when(mockCreds).applyRequestMetadata(same(method), any(Attributes.class),
same(mockExecutor), any(MetadataApplier.class));
FailingClientStream stream =
(FailingClientStream) transport.newStream(method, origHeaders, callOptions);
verify(mockTransport, never()).newStream(method, origHeaders, callOptions);
assertSame(error, stream.getError());
}
示例13: getNameResolverParams
import io.grpc.Attributes; //导入依赖的package包/类
@Override
protected Attributes getNameResolverParams() {
int defaultPort;
switch (negotiationType) {
case PLAINTEXT:
defaultPort = GrpcUtil.DEFAULT_PORT_PLAINTEXT;
break;
case TLS:
defaultPort = GrpcUtil.DEFAULT_PORT_SSL;
break;
default:
throw new AssertionError(negotiationType + " not handled");
}
return Attributes.newBuilder()
.set(NameResolver.Factory.PARAMS_DEFAULT_PORT, defaultPort).build();
}
示例14: updateSubchannelAddresses_newAddressConnects
import io.grpc.Attributes; //导入依赖的package包/类
@Test
public void updateSubchannelAddresses_newAddressConnects() {
ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
call.start(mockCallListener, new Metadata()); // Create LB
ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null);
verify(mockLoadBalancerFactory).newLoadBalancer(helperCaptor.capture());
Helper helper = helperCaptor.getValue();
Subchannel subchannel = helper.createSubchannel(servers.get(0), Attributes.EMPTY);
subchannel.requestConnection();
MockClientTransportInfo t0 = newTransports.poll();
t0.listener.transportReady();
helper.updateSubchannelAddresses(subchannel, servers.get(1));
subchannel.requestConnection();
MockClientTransportInfo t1 = newTransports.poll();
t1.listener.transportReady();
}
示例15: serverPlaintext
import io.grpc.Attributes; //导入依赖的package包/类
/**
* Create a server plaintext handler for gRPC.
*/
public static ProtocolNegotiator serverPlaintext() {
return new ProtocolNegotiator() {
@Override
public Handler newHandler(final GrpcHttp2ConnectionHandler handler) {
class PlaintextHandler extends ChannelHandlerAdapter implements Handler {
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
// Set sttributes before replace to be sure we pass it before accepting any requests.
handler.handleProtocolNegotiationCompleted(Attributes.newBuilder()
.set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, ctx.channel().remoteAddress())
.build());
// Just replace this handler with the gRPC handler.
ctx.pipeline().replace(this, null, handler);
}
@Override
public AsciiString scheme() {
return Utils.HTTP;
}
}
return new PlaintextHandler();
}
};
}