java tls 实例_grpc加密TLS初体验(go、java版本)
grpc加密TLS初體驗(yàn)(go、java版本)
grpc-go、java的安裝編譯helloworld可以參考如下文章
openssl的安裝、生成秘鑰證書可以參考如下文章
示例代碼go版本
服務(wù)端代碼
package main
import (
"fmt"
"log"
"net"
pb "github.com/grpc/grpc-common/go/helloworld"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
const (
port = ":50051"
)
type server struct{}
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
fmt.Println("--->>> request name = ", in.Name)
return &pb.HelloReply{Message: "--->>> Hello " + in.Name}, nil
}
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
fmt.Println(">>> server is starting in 127.0.0.1 and port " + port + " >>>")
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
creds, err := credentials.NewServerTLSFromFile("D:/BaiduYunDownload/server1.pem", "D:/BaiduYunDownload/server1.key")
if err != nil {
fmt.Println("Failed to generate credentials: ", err)
}
s.Serve(creds.NewListener(lis))
}
客戶端代碼
package?main
import?(
"log"
"os"
pb?"github.com/grpc/grpc-common/go/helloworld"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
const?(
address?????=?"127.0.0.1:50051"
defaultName?=?"world"
)
func?main()?{
var?opts?[]grpc.DialOption
var?creds?credentials.TransportAuthenticator
var?err?error
creds,?err?=?credentials.NewClientTLSFromFile("D:/BaiduYunDownload/ca.pem",?"x.test.youtube.com")
if?err?!=?nil?{
log.Fatalf("Failed?to?create?TLS?credentials?%v",?err)
}
opts?=?append(opts,?grpc.WithTransportCredentials(creds))
conn,?err?:=?grpc.Dial(address,?opts...)
if?err?!=?nil?{
log.Fatalf("did?not?connect:?%v",?err)
}
log.Printf(">>>?connect?success?>>>")
defer?conn.Close()
c?:=?pb.NewGreeterClient(conn)
name?:=?defaultName
if?len(os.Args)?>?1?{
name?=?os.Args[1]
}
r,?err?:=?c.SayHello(context.Background(),?&pb.HelloRequest{Name:?name})
if?err?!=?nil?{
log.Fatalf("could?not?greet:?%v",?err)
}
log.Printf("Greeting:?%s",?r.Message)
}
示例代碼java版本
服務(wù)端代碼:
packageio.grpc.examples.helloworld;
importio.grpc.ServerImpl;
importio.grpc.stub.StreamObserver;
importio.grpc.transport.netty.NettyServerBuilder;
importio.netty.handler.ssl.SslContext;
importjava.io.File;
importjava.util.logging.Logger;
public classHelloWorldServer {
private static finalLoggerlogger= Logger
.getLogger(HelloWorldServer.class.getName());
private int port= 50051;
privateServerImplserver;
private voidstart()throwsException {
@SuppressWarnings("deprecation")
SslContext sslContext = SslContext.newServerContext(newFile(
"D:/BaiduYunDownload/server3.pem"),newFile(
"D:/BaiduYunDownload/server3_pkcs8.key"));
server= NettyServerBuilder.forPort(port).sslContext(sslContext)
.addService(GreeterGrpc.bindService(newGreeterImpl())).build()
.start();
logger.info("Server started, listening on "+port);
Runtime.getRuntime().addShutdownHook(newThread() {
@Override
public voidrun() {
System.err
.println("*** shutting down gRPC server since JVM is shutting down");
HelloWorldServer.this.stop();
System.err.println("*** server shut down");
}
});
}
private voidstop() {
if(server!=null) {
server.shutdown();
}
}
public static voidmain(String[] args)throwsException {
finalHelloWorldServer server =newHelloWorldServer();
server.start();
}
private classGreeterImplimplementsGreeterGrpc.Greeter {
@Override
public voidsayHello(HelloRequest req,
StreamObserver responseObserver) {
System.out.println("--->>> name = "+ req.getName());
HelloResponse reply = HelloResponse.newBuilder()
.setMessage("Hello "+ req.getName()).build();
responseObserver.onValue(reply);
responseObserver.onCompleted();
}
}
}
客戶端代碼:
packageio.grpc.examples.helloworld;
importio.grpc.ChannelImpl;
importio.grpc.transport.netty.NegotiationType;
importio.grpc.transport.netty.NettyChannelBuilder;
importio.netty.handler.ssl.SslContext;
importjava.io.File;
importjava.security.NoSuchAlgorithmException;
importjava.util.concurrent.TimeUnit;
importjava.util.logging.Level;
importjava.util.logging.Logger;
importjavax.net.ssl.SSLException;
public classHelloWorldClient {
private static finalLoggerlogger= Logger
.getLogger(HelloWorldClient.class.getName());
private finalChannelImplchannel;
private finalGreeterGrpc.GreeterBlockingStubblockingStub;
publicHelloWorldClient(String host,intport)throwsSSLException,
NoSuchAlgorithmException {
@SuppressWarnings("deprecation")
//這里要注意下由于java版本的沒有提供像go那樣的可以指定域名
// java版本源代碼中把host傳入作為證書域名
//域名是在證書生成的過程中自己輸入的
SslContext sslContext = SslContext.newClientContext(newFile(
"D:/BaiduYunDownload/ca3.pem"));
channel= NettyChannelBuilder.forAddress(host, port)
.sslContext(sslContext).negotiationType(NegotiationType.TLS)
.build();
blockingStub= GreeterGrpc.newBlockingStub(channel);
}
public voidshutdown()throwsInterruptedException {
channel.shutdown().awaitTerminated(5, TimeUnit.SECONDS);
}
public voidgreet(String name) {
try{
logger.info("Will try to greet "+ name);
HelloRequest request = HelloRequest.newBuilder().setName(name)
.build();
HelloResponse response =blockingStub.sayHello(request);
logger.info("Greeting: "+ response.getMessage());
}catch(RuntimeException e) {
logger.log(Level.WARNING,"RPC failed", e);
return;
}
}
public static voidmain(String[] args)throwsException {
HelloWorldClient client =newHelloWorldClient("localhost", 50051);
try{
String user ="world";
if(args.length> 0) {
user = args[0];
}
client.greet(user);
}finally{
client.shutdown();
}
}
}
示例代碼下載
有疑問加站長微信聯(lián)系(非本文作者)
總結(jié)
以上是生活随笔為你收集整理的java tls 实例_grpc加密TLS初体验(go、java版本)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 猎豹浏览器怎么查看历史记录 猎豹浏览器历
- 下一篇: 本地提交spark_Spark 数据本地