A/B实验Java SDK

本文为您介绍如何使用A/B实验的Java SDK进行实验分流,并获取实验相关的参数配置信息。

前提条件

添加依赖项

使用Java编写客户端代码时,在Maven工程中使用A/B实验SDK,必须在pom.xml文件<dependencies>中添加如下依赖,示例如下所示:

  • pai-abtest-sdk

    <dependency>
      <groupId>com.aliyun.openservices.aiservice</groupId>
      <artifactId>pai-abtest-sdk</artifactId>
      <version>1.0.0</version>
    </dependency>
  • okhttp

    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.12.0</version>
    </dependency>

使用示例

package com.aliyun.openservices.paiabtest;

import com.aliyun.openservices.paiabtest.api.ApiClient;
import com.aliyun.openservices.paiabtest.api.Configuration;
import com.aliyun.openservices.paiabtest.model.ExperimentContext;
import com.aliyun.openservices.paiabtest.model.ExperimentResult;

import java.util.HashMap;
import java.util.Map;

public class ExperimentTest {
    static ExperimentClient experimentClient;

    public static void main(String[] args) throws Exception {
        // set up experiment client
        String regionId = "cn-beijing";
        String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        Configuration configuration = new Configuration(regionId, accessId, accessKey);
        ApiClient apiClient = new ApiClient(configuration);
        experimentClient = new ExperimentClient(apiClient);

        // init load experiment data
        experimentClient.init();

        // set up experiment context
        ExperimentContext experimentContext = new ExperimentContext();
        experimentContext.setRequestId("<req_id>");
        // set uid
        experimentContext.setUid("<uid>");
        // set filter params for condition filter match
        Map<String, Object> filterParams = new HashMap<>();
        filterParams.put("sex", "male");
        experimentContext.setFilterParams(filterParams);

        // match experiment
        ExperimentResult experimentResult =  experimentClient.matchExperiment("<DefaultProject>", experimentContext);

        // print experiment info
        System.out.println(experimentResult.info());
        // print exp id
        System.out.println(experimentResult.getExpId());
        // print exp params
        System.out.println(experimentResult.getExperimentParams().get("recall_v", "not exist"));
        System.out.println(experimentResult.getExperimentParams().get("rank_v", "not exist"));
        System.out.println(experimentResult.getExperimentParams().get("male_v", "not exist"));
    }
}

其中:

  • regionId:地域ID,例如华东1(杭州)配置为cn-hangzhou。

  • <req_id>:自定义配置请求ID。

  • <uid>:实验分流ID标识。可以是用户侧的UserID,也可以是设备ID等。

  • filterParams.put("sex", "male"):其中sexmale为实验分流参数,请根据实际情况进行修改。

  • <DefaultProject>:A/B实验项目名称。请前往A/B实验的项目管理 > 实现项目页面,查看项目名称。具体操作,请参见新建实验项目