下面列出了io.grpc.Server#start ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main(String[] arg) {
try {
Server server = ServerBuilder.forPort(8080)
.addService(new EmployeeService())
.build();
System.out.println("Starting gRPC Server Service ...");
server.start();
System.out.println("Server has started at port: 8080");
System.out.println("Following services are available: ");
server.getServices().stream()
.forEach(
s -> System.out.println("Service Name: " + s.getServiceDescriptor().getName())
);
server.awaitTermination();
} catch (Exception e) {
e.printStackTrace();
}
}
public Server startServer() throws IOException {
ServerInterceptor headersInterceptor = new TracingMetadataUtils.ServerHeadersInterceptor();
NettyServerBuilder b =
NettyServerBuilder.forPort(workerOptions.listenPort)
.addService(ServerInterceptors.intercept(actionCacheServer, headersInterceptor))
.addService(ServerInterceptors.intercept(bsServer, headersInterceptor))
.addService(ServerInterceptors.intercept(casServer, headersInterceptor))
.addService(ServerInterceptors.intercept(capabilitiesServer, headersInterceptor));
if (workerOptions.tlsCertificate != null) {
b.sslContext(getSslContextBuilder(workerOptions).build());
}
if (execServer != null) {
b.addService(ServerInterceptors.intercept(execServer, headersInterceptor));
} else {
logger.atInfo().log("Execution disabled, only serving cache requests");
}
Server server = b.build();
logger.atInfo().log("Starting gRPC server on port %d", workerOptions.listenPort);
server.start();
return server;
}
@Override
public Void call() throws Exception {
OzoneConfiguration ozoneConfiguration = createOzoneConfiguration();
CsiConfig csiConfig = ozoneConfiguration.getObject(CsiConfig.class);
OzoneClient rpcClient = OzoneClientFactory.getRpcClient(ozoneConfiguration);
EpollEventLoopGroup group = new EpollEventLoopGroup();
if (csiConfig.getVolumeOwner().isEmpty()) {
throw new IllegalArgumentException(
"ozone.csi.owner is not set. You should set this configuration "
+ "variable to define which user should own all the created "
+ "buckets.");
}
Server server =
NettyServerBuilder
.forAddress(new DomainSocketAddress(csiConfig.getSocketPath()))
.channelType(EpollServerDomainSocketChannel.class)
.workerEventLoopGroup(group)
.bossEventLoopGroup(group)
.addService(new IdentitiyService())
.addService(new ControllerService(rpcClient,
csiConfig.getDefaultVolumeSize()))
.addService(new NodeService(csiConfig))
.build();
server.start();
server.awaitTermination();
rpcClient.close();
return null;
}
static public void main(String [] args) throws IOException, InterruptedException {
JwtServerInterceptor jwtInterceptor = new JwtServerInterceptor(Constant.JWT_SECRET);
Server greetingServer = ServerBuilder.forPort(8080)
.addService(ServerInterceptors.intercept(new GreetingServiceImpl(), jwtInterceptor, new TraceIdServerInterceptor()))
.build();
greetingServer.start();
System.out.println("Server started!");
greetingServer.awaitTermination();
}
private static void startServerOnPort(int port) {
ServerBuilder<?> serverBuilder = NettyServerBuilder.forAddress(
new InetSocketAddress("127.0.0.1", port));
serverBuilder.addService(new MyTccEventServiceImpl(connected.get(port), eventsMap.get(port), delays.get(port)));
Server server = serverBuilder.build();
try {
server.start();
servers.put(port, server);
} catch (Exception ex) {
fail(ex.getMessage());
}
}
@Test
public void serverRunsAndRespondsCorrectly() throws ExecutionException,
IOException,
InterruptedException,
TimeoutException {
final String name = UUID.randomUUID().toString();
Server server = ServerBuilder.forPort(9999)
.addService(new GreeterImpl())
.build();
server.start();
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.getPort())
.usePlaintext(true)
.build();
GreeterGrpc8.GreeterCompletableFutureStub stub = GreeterGrpc8.newCompletableFutureStub(channel);
CompletableFuture<HelloResponse> response = stub.sayHello(HelloRequest.newBuilder().setName(name).build());
await().atMost(3, TimeUnit.SECONDS).until(() -> response.isDone() && response.get().getMessage().contains(name));
channel.shutdown();
channel.awaitTermination(1, TimeUnit.MINUTES);
channel.shutdownNow();
server.shutdown();
server.awaitTermination(1, TimeUnit.MINUTES);
server.shutdownNow();
}
/**
* Starts the server on given port
*
* @param evaluator an implementation of {@link IObjectEvaluator} with
* {@link ComponentInstance} and Double
* @param input {@link PCSBasedOptimizerInput}
* @throws IOException
* @throws InterruptedException
*/
public static void start(final IObjectEvaluator<ComponentInstance, Double> evaluator, final PCSBasedOptimizerInput input) throws IOException, InterruptedException {
PCSBasedOptimizerConfig config = PCSBasedOptimizerConfig.get("conf/smac-optimizer-config.properties");
Integer port = config.getPort();
Server server = ServerBuilder.forPort(port).addService(new PCSBasedOptimizerServiceImpl(evaluator, input)).build();
server.start();
server.awaitTermination();
}
/**
* main method (and init()) is not actually needed, but helpful for debugging
* purposes
*
* @param args
* @throws Exception
*/
public static void main(final String[] args) throws Exception {
init();
Server server = ServerBuilder.forPort(8080).addService(new PCSBasedOptimizerServiceImpl(evaluator, input)).build();
server.start();
server.awaitTermination();
}
static public void main(String [] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(8080)
.addService(new GreetingServiceImpl()).build();
System.out.println("Starting server...");
server.start();
System.out.println("Server started!");
server.awaitTermination();
}
static public void main(String[] args) throws IOException, InterruptedException {
UnknownStatusDescriptionInterceptor unknownStatusDescriptionInterceptor = new UnknownStatusDescriptionInterceptor(Arrays.asList(
IllegalArgumentException.class
));
Server server = ServerBuilder.forPort(8080)
.addService(ServerInterceptors.intercept(new ErrorServiceImpl(), unknownStatusDescriptionInterceptor))
.build();
System.out.println("Starting server...");
server.start();
System.out.println("Server started!");
server.awaitTermination();
}
public static void main(String[] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(8081)
.addService(new GreetingServiceImpl())
.build();
server.start();
server.awaitTermination();
}
public static void main(String[] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(8081)
.addService(new GreetingServiceImpl())
.build();
server.start();
server.awaitTermination();
}
@Produces
@ApplicationScoped
public Lifecycle storageGrpcServer(
HostInfo storageLocalHost,
KeyValueStoreGrpc.KeyValueStoreImplBase storageStoreGrpcImpl,
AsyncBiFunctionServiceGrpc.AsyncBiFunctionServiceImplBase storageAsyncBiFunctionServiceGrpcImpl
) {
UnknownStatusDescriptionInterceptor unknownStatusDescriptionInterceptor =
new UnknownStatusDescriptionInterceptor(
ImmutableMap.of(
IllegalArgumentException.class, Status.INVALID_ARGUMENT,
IllegalStateException.class, Status.FAILED_PRECONDITION,
InvalidStateStoreException.class, Status.FAILED_PRECONDITION,
Throwable.class, Status.INTERNAL
)
);
Server server = ServerBuilder
.forPort(storageLocalHost.port())
.addService(
ServerInterceptors.intercept(
storageStoreGrpcImpl,
unknownStatusDescriptionInterceptor
)
)
.addService(
ServerInterceptors.intercept(
storageAsyncBiFunctionServiceGrpcImpl,
unknownStatusDescriptionInterceptor
)
)
.build();
return new Lifecycle() {
@Override
public void start() {
try {
server.start();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public void stop() {
ConcurrentUtil
.<Server>consumer(Server::awaitTermination)
.accept(server.shutdown());
}
@Override
public boolean isRunning() {
return !(server.isShutdown() || server.isTerminated());
}
};
}
public Arktika(Config config) throws Exception
{
this.config = config;
logger.info(String.format("Starting Arktika version %s", Globals.VERSION));
config.require("selected_field");
config.require("layer_count");
layer_count = config.getInt("layer_count");
selected_field = config.getInt("selected_field");
params = NetworkParams.loadFromConfig(config);
if (config.isSet("pool_host_list"))
{
pool_client = new PoolClientFailover(config, this);
}
else
{
pool_client = new PoolClient(config, this);
}
// this is a bad idea, don't use this. It eats all the cpu doing
// record keeping
if (config.getBoolean("display_timerecord"))
{
time_record = new TimeRecord();
TimeRecord.setSharedRecord(time_record);
}
loadField();
pool_client.subscribe();
stubo = new Stubo(composit_source, selected_field);
if (config.isSet("benchmark_layer"))
{
startBenchmark();
return;
}
startFieldWorkers();
if (!config.getBoolean("nolisten"))
{
Server s = ServerBuilder
.forPort(2311)
.addService(stubo)
.build();
s.start();
}
//new QueuePruner().start();
}
public MrPlow(Config config) throws Exception
{
this.config = config;
logger.info(String.format("Starting MrPlow version %s", Globals.VERSION));
config.require("pool_address");
config.require("pool_fee");
config.require("db_type");
config.require("db_path");
min_diff = config.getIntWithDefault("min_diff", 22);
params = NetworkParams.loadFromConfig(config);
if (config.getBoolean("display_timerecord"))
{
time_record = new TimeRecord();
TimeRecord.setSharedRecord(time_record);
}
int port = config.getIntWithDefault("mining_pool_port",23380);
agent = new MiningPoolServiceAgent(this);
double pool_fee = config.getDouble("pool_fee");
double duck_fee = config.getDoubleWithDefault("pay_the_duck", 0.0);
TreeMap<String, Double> fixed_fee_map = new TreeMap<>();
fixed_fee_map.put( AddressUtil.getAddressString(params.getAddressPrefix(), getPoolAddress()), pool_fee );
if (duck_fee > 0.0)
{
fixed_fee_map.put( "snow:crqls8qkumwg353sfgf5kw2lw2snpmhy450nqezr", duck_fee);
}
loadDB();
PPLNSState pplns_state = null;
try
{
pplns_state = PPLNSState.parseFrom(db.getSpecialMap().get("pplns_state"));
logger.info(String.format("Loaded PPLNS state with %d entries", pplns_state.getShareEntriesCount()));
}
catch(Throwable t)
{
logger.log(Level.WARNING, "Unable to load PPLNS state, starting fresh:" + t);
}
share_manager = new ShareManager(fixed_fee_map, pplns_state);
report_manager = new ReportManager();
subscribe();
Server s = ServerBuilder
.forPort(port)
.addService(agent)
.build();
if (config.isSet("rpc_port"))
{
JsonRpcServer json_server = new JsonRpcServer(config, false);
new MrPlowJsonHandler(this).registerHandlers(json_server);
}
s.start();
loop = new PlowLoop();
loop.start();
}
/**
* Example minimal xDS implementation using the java-control-plane lib.
*
* @param arg command-line args
*/
public static void main(String[] arg) throws IOException, InterruptedException {
SimpleCache<String> cache = new SimpleCache<>(node -> GROUP);
cache.setSnapshot(
GROUP,
Snapshot.create(
ImmutableList.of(
Cluster.newBuilder()
.setName("cluster0")
.setConnectTimeout(Duration.newBuilder().setSeconds(5))
.setType(DiscoveryType.STATIC)
.addHosts(Address.newBuilder()
.setSocketAddress(SocketAddress.newBuilder().setAddress("127.0.0.1").setPortValue(1234)))
.build()),
ImmutableList.of(),
ImmutableList.of(),
ImmutableList.of(),
ImmutableList.of(),
"1"));
DiscoveryServer discoveryServer = new DiscoveryServer(cache);
ServerBuilder builder = NettyServerBuilder.forPort(12345)
.addService(discoveryServer.getAggregatedDiscoveryServiceImpl())
.addService(discoveryServer.getClusterDiscoveryServiceImpl())
.addService(discoveryServer.getEndpointDiscoveryServiceImpl())
.addService(discoveryServer.getListenerDiscoveryServiceImpl())
.addService(discoveryServer.getRouteDiscoveryServiceImpl());
Server server = builder.build();
server.start();
System.out.println("Server has started on port " + server.getPort());
Runtime.getRuntime().addShutdownHook(new Thread(server::shutdown));
Thread.sleep(10000);
cache.setSnapshot(
GROUP,
Snapshot.create(
ImmutableList.of(
Cluster.newBuilder()
.setName("cluster1")
.setConnectTimeout(Duration.newBuilder().setSeconds(5))
.setType(DiscoveryType.STATIC)
.addHosts(Address.newBuilder()
.setSocketAddress(SocketAddress.newBuilder().setAddress("127.0.0.1").setPortValue(1235)))
.build()),
ImmutableList.of(),
ImmutableList.of(),
ImmutableList.of(),
ImmutableList.of(),
"1"));
server.awaitTermination();
}
@Ignore
// issue when moved up to latest netty http://openjdk.5641.n7.nabble.com/sun-security-ssl-ProtocolVersion-valueOf-in-Java8-and-TLSv1-3-td350186.html
@Test
public void selfSignedTLSCertTest() throws Exception {
AtomicBoolean handshakeOccured = new AtomicBoolean(false);
TLSCertificateBuilder certBuilder = new TLSCertificateBuilder();
TLSCertificateKeyPair serverCert = certBuilder.serverCert("localhost");
File serverCertFile = createFile("server-cert.pem", serverCert.getCertPEMBytes());
File serverKeyFile = createFile("server-key.pem", serverCert.getKeyPemBytes());
TLSCertificateKeyPair clientCert = certBuilder.clientCert();
File clientCertFile = createFile("client-cert.pem", clientCert.getCertPEMBytes());
File clientKeyFile = createFile("client-key.pem", clientCert.getKeyPemBytes());
Server server = NettyServerBuilder.forPort(0).addService(new MockEndorser()).
intercept(mutualTLSInterceptor(clientCert.getCertDERBytes(), handshakeOccured))
.sslContext(GrpcSslContexts.forServer(serverCertFile, serverKeyFile).protocols(TLS_PROTOCOL)
.trustManager(clientCertFile)
.clientAuth(ClientAuth.REQUIRE)
.build()).build();
server.start();
if (vendor.contains("IBM")) {
// The TLS handshake doesn't work with IBM JRE, skipping
server.shutdown();
return;
}
NettyChannelBuilder channelBuilder = NettyChannelBuilder
.forAddress("localhost", server.getPort())
.sslContext(getSslContextBuilder(clientCertFile, clientKeyFile, serverCertFile).protocols(TLS_PROTOCOL).build())
.negotiationType(NegotiationType.TLS);
ManagedChannel chan = channelBuilder.build();
ProposalPackage.SignedProposal prop = ProposalPackage.SignedProposal.getDefaultInstance();
EndorserGrpc.newBlockingStub(chan).processProposal(prop);
// Ensure that TLS handshake occurred
Assert.assertTrue("Handshake didn't occur", handshakeOccured.get());
chan.shutdown();
server.shutdown();
}
@SneakyThrows
private void startServer(Server server) {
server.start();
log.info("Server has been starting {}", server);
publisher.publishEvent(new NettyServerStartingEvent(applicationContext, server));
}
public static void main(String[] args) throws InterruptedException, IOException {
Server server = ServerBuilder.forPort(9090).addService(new ChatServiceImpl()).build();
server.start();
server.awaitTermination();
}
public static void main(String[] args) throws InterruptedException, IOException {
Server server = ServerBuilder.forPort(8080).addService(new MetricsServiceImpl()).build();
server.start();
server.awaitTermination();
}