使用手册

下面通过代码说明该 SDK 的使用方法,一个完整的示例在这里获取
在这个简单的示例中,服务端的入口在 server 包下的类 Server 中,客户端的入口在 client 包下的类 Client 中,无需任何额外的配置就能直接运行它

Server

1. 接口定义:

示例:

public class EchoServer {
    @ThriftService("EchoServer")
    public interface Iface {
        @ThriftMethod("echo")
        String echo(String input);
    }

    // 异步接口,如果不需要可以不定义
    @ThriftService("EchoServer")
    public interface AsyncIface {
        @ThriftMethod("echo")
        ListenableFuture<String> echo(String input);    
    }
}

定义了两个接口 Iface AsyncIface,一个用于同步 Client,一个用于异步 Client

2. 接口实现:

示例:

public class EchoServerImpl implements EchoServer.Iface {
    @Override
    public String echo(String input) {
        return input;
    }
}

3. 服务启动:

示例:

public class Server {
    public static void main(String[] args) {
        ServerConfig<EchoServerImpl> config = new ServerConfig.Builder<>(EchoServerImpl.class)
                .registryFactory(new ServiceCenterRegistryFactory(EchoServerImpl.class))
                .port(12346).build();
        Bootstrap<EchoServerImpl> bootstrap = new Bootstrap<>(config);
        bootstrap.start();
    }
}

如上所示,通常情况下 ServerConfig 我们只需配置端口号,线程数和 ServiceCenterRegistryFactory

ServerConfig 可以配置的参数可以看看 builder 里面的代码:

private Class<T> clazz; // 实现 Server 的 Class
private Endpoint endpoint; // 包含 Server 信息的 Endpoint,可以不配置,默认是本机 ip
private int threadPoolSize; // Server 处理业务的线程池大小,建议按需配置,默认大小为 5
private List<ThriftEventHandler> eventHandlers; // Swift 的 Event Handler,建议默认值
private RegistryFactory registryFactory; // 注册工厂,需要使用 ServiceCenterRegistryFactory
private InvocationHandler serviceProxy; // 如果用户需要对 Server impl 用反射再封装,可以用这个
private ThriftServerConfig thriftServerConfig; // Swift 的 Server 配置,建议默认值
private String portKey; // 端口号的 properties key,默认 port,需要在 Registry 读取端口号
private String threadPoolSizeKey; // 线程数的 properties key,如果需要在 registry 读取线程数
private MetricsFactory metricsFactory; // metricsFactory,用户监控
private int port; // 端口号

然后我们可以用 Bootstrap 启动 Server:

Bootstrap<EchoServerImpl> bootstrap = new Bootstrap<>(config);
bootstrap.start();

Bootstrap 有两个构造函数,上面例子会自己去反射调用实例化 ServerImpl,如果有自己特殊的需求,可以把实例化好的对象放到第二个参数

new Bootstrap<>(config, serverImpl);

Client

示例:

public class Client {
    public static void main(String[] args) throws InterruptedException {
        // client 调用同步接口
        String request = "Hello Xiaomi!";
        ClientConfig<EchoServer.Iface> syncClientConfig =
                new ClientConfig.ClientConfigBuilder<>(EchoServer.Iface.class)
                        .registryFactory(new ServiceCenterRegistryFactory(EchoServer.Iface.class))
                        .build();
        EchoServer.Iface newSyncClient = new SwiftClientManager<>(syncClientConfig).createClient();
        String response = newSyncClient.echo(request);
        System.out.println(response);

        // client 调用异步接口
        String asyncRequest = "Hello Xiaomi!(async)";
        ClientConfig<EchoServer.AsyncIface> asyncIfaceClientConfig =
                new ClientConfig.ClientConfigBuilder<>(EchoServer.AsyncIface.class)
                        .registryFactory(new ServiceCenterRegistryFactory(EchoServer.Iface.class))
                        .build();
        EchoServer.AsyncIface newAsyncClinet = new SwiftClientManager<>(asyncIfaceClientConfig).createClient();
        ListenableFuture<String> future = newAsyncClinet.echo(asyncRequest);
        Futures.addCallback(future, new FutureCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println(result);
            }

            @Override
            public void onFailure(Throwable t) {
                t.printStackTrace();
            }
        });
        Thread.sleep(1000);
    }
}

如上所示, 通常情况下 ClientConfig 我们只需要配置 ServiceCenterRegistryFactory,其他使用默认值即可

ClientConfig 可配置参数可以看 CliengConfig builder 代码:

private Class<Iface> ifaceClazz;
private EndpointPoolProviderFactory endpointPoolProviderFactory; // 建议默认值,用于提供和更新 Server 信息
private EndpointGroupingStrategyFactory endpointGroupingStrategyFactory; // 建议默认值,用于 Server 分组
private LoadBalancerFactory loadBalancerFactory; // 建议默认值,用于 Loadbalancer
private DefaultInvokerFactory invokerFactory; // 建议默认值
private ConnectionManagerFactory connectionManagerFatory; // 建议默认值,管理连接
private ConnectionConfigFactory connectionConfigFactory; // 建议默认值
private RegistryFactory registryFactory; // 请使用 ServiceCenterRegistryFactory
private MetricsFactory metricsFactory; //  监控

然后我们可以开始创建 Client 对象:

EchoServer.Iface newSyncClient = new SwiftClientManager<>(syncClientConfig).createClient();
String response = newSyncClient.echo(request);
System.out.println(response);

Registry 服务注册与发现

前面不管 Server 还是 Client 都提到了 ServiceCenterRegistryFactory,需要在 application.conf 配置中配置如下参数,比如:

# 机构认证标识 ak(必填)
registry.zookeeper.accesskey=""
# 机构认证标识 sk(必填)
registry.zookeeper.secretkey=""
# 注册中心监控周期,建议默认值 10s(选填)
registry.scheduler.step.seconds=10
# 注册超时时间,建议默认值 5000ms(选填)
registry.connection.timeout.milliseconds=5000
# 注册中心 URL(必填)
# aws-北京的 URL 为 https://cnbj-sc.rpc.cloud.mi.com,金山云的 URL 为 https://cnbj6-sc.rpc.cloud.mi.com
registry.servicecenter.domain="https://cnbj6-sc.rpc.cloud.mi.com"

注:client必须使用和server同一个用户组的AK/SK才能够发现服务。

ak 和 sk 的获取方式参见获取 ak 和 sk

服务启动成功后,Client 也会在这里读取相关的 Server 信息, Server 需要与注册中心同一机房

Metrics 监控中心

Metrics 作为系统的监控中心, 主要监控指标有调用方法时间、次数及异常次数等, 已经实现的监控系统有 Open-Falcon , 如下所示,我们还可以通过实现 Metrics 实现自己的监控中心

Metrics

public void count(Counter counter)
public void countDuration(Method method, long duration): 统计方法执行时间,次数
public void countException(Method method, Throwable throwable):统计异常次数

Counter

private String name:Counter name,表示统计的一个指标 Key
private long longValue:调用次数
private String tags:标签
private long time:执行时间
....

使用监控中心,只需要在初始化 ClientConfig 时传入相应的工厂类, 如下所示

ClientConfig<EchoServer.Iface> syncClientConfig =
                new ClientConfig.ClientConfigBuilder<>(EchoServer.Iface.class)
                        .registryFactory(new ZookeeperRegistryFactory(EchoServer.Iface.class))
                        .metricsFactory(new OpenFalconMetricsFactory(SwiftMetricsUtil.getClientCounterPrefix(EchoServer.Iface.class), '-'))
                        .build();
EchoServer.Iface newSyncClient = new SwiftClientManager<>(syncClientConfig).createClient();

目前支持的监控项有:

Client

thriftcli-${ifaceClassName}-${methodName}:client 调用 methodname 方法的时间,次数
thriftcli-${ifaceClassName}-${methodName}_fail:namethodName 调用失败次数
thriftcli-${ifaceClassName}-exception-${exceptionName}:exceptionName 异常的调用次数

Server

method/${methodName}:methodName 调用次数,时间
method/ALL_THRIFT_METHODS:所有 method 调用次数,时间
method/${methodName}_fail:methodName 调用失败次数
exception/${exceptionName}: exception 次数 
method/ALL_THRIFT_METHODS_FAIL: 所有 method 调用失败次数

使用监控中心需要以下配置:

  • 用户使用 Open-Falcon :
metric.falcon.agent.collection.url="http://127.0.0.1:1988/v1/push" //数据采集 URL,默认值为 "http://127.0.0.1:1988/v1/push"
metric.falcon.agent.push.period.time.second=300  //数据采集汇报周期,默认值为300
metric.falcon.agent.pushon=true  //推送开关,是否推送数据到 Agent,默认值为 true
metric.falcon.agent.http.connection.timeout.milliseconds=300 //通过 Http 协议推送数据到本地 Agent 连接超时时间,默认值为300
metric.falcon.agent.jobtags="" //jobtag

如果上述默认值不满足要求,用户可以在类路径下的 application.conf 中配置上述参数

results matching ""

    No results matching ""