實(shí)現(xiàn)Kong的Java管理API - Kong最佳實(shí)踐

Kong提供了Http的管理API祠墅,可以實(shí)現(xiàn)對(duì)Kong的管理难审。我們利用Kong的Amin API沙绝,實(shí)現(xiàn)一套JAVA的管理API慢蜓。這里以添加一個(gè)Service和Route為示例:

使用retrofit2實(shí)現(xiàn)

添加Maven依賴(lài)

<dependency>
            <groupId>com.squareup.retrofit2</groupId>
            <artifactId>retrofit</artifactId>
            <version>${retrofit.version}</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.retrofit2</groupId>
            <artifactId>converter-gson</artifactId>
            <version>${retrofit.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>com.google.code.gson</groupId>
                    <artifactId>gson</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.1</version>
        </dependency>

實(shí)現(xiàn)kong客戶(hù)端的架子

添加Kong客戶(hù)端

@Data
public class KongClient {

    private ServiceService serviceService;
    private RouteService routeService;

    public KongClient(String adminUrl) {

        if (adminUrl == null || adminUrl.isEmpty()) {
            throw new IllegalArgumentException("The adminUrl cannot be null or empty!");
        }
        RetrofitServiceCreator retrofitServiceCreatorForAdminUrl = new RetrofitServiceCreator(adminUrl);
        {
            serviceService = retrofitServiceCreatorForAdminUrl.create(ServiceService.class,RetrofitServiceService.class);
            routeService = retrofitServiceCreatorForAdminUrl.create(RouteService.class,RetrofitRouteService.class);
        }
  }
}

添加Retrofit處理類(lèi)

public class RetrofitServiceCreator {

    private Retrofit retrofit;


    // -------------------------------------------------------------------

    public RetrofitServiceCreator(String baseUrl) {

        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(initOkHttpClient(baseUrl.toLowerCase().startsWith("https"))) // support https
                .addConverterFactory(CustomGsonConverterFactory.create()) // replace GsonConverterFactory

    }

    // -------------------------------------------------------------------

    @SuppressWarnings("unchecked")
    public <T> T create(Class<T> serviceInterface, Class<?> retrofitServiceInterface) {
        Object proxied = retrofit.create(retrofitServiceInterface);
        return (T) Proxy.newProxyInstance(
                RetrofitServiceCreator.class.getClassLoader(),
                new Class[] { serviceInterface },
                new RetrofitBodyExtractorInvocationHandler(proxied));
    }

    public <T> T createRetrofitService(Class<T> retrofitServiceInterface) {
        return retrofit.create(retrofitServiceInterface);
    }

    // -------------------------------------------------------------------

    private OkHttpClient initOkHttpClient(boolean supportHttps) {

        if(supportHttps) {
            HttpsUtil.SSLParams sslParams = HttpsUtil.getSslSocketFactory(null, null, null);
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                    .build();
            return okHttpClient;
        }

        return new OkHttpClient.Builder().build();
    }
}

添加動(dòng)態(tài)代理處理類(lèi)

@Slf4j
public class RetrofitBodyExtractorInvocationHandler implements InvocationHandler {

    private Object proxied;

    public RetrofitBodyExtractorInvocationHandler(Object proxied) {
        this.proxied = proxied;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        Class<?>[] parameterTypes = method.getParameterTypes();
        Method method1 = proxied.getClass().getMethod(methodName, parameterTypes);
        Call call = (Call) method1.invoke(proxied, args);
        Response response = call.execute();
        log.debug("Http Request:  " + response.raw().request());
        log.debug("Http Response: " + response.raw().toString());
        if(!response.isSuccessful()) {
            throw new KongClientException(response.errorBody() != null ? response.errorBody().string() : String.valueOf(response.code()));
        }
        return response.body();
    }
}

添加自定義JSON轉(zhuǎn)換工廠

class CustomGsonConverterFactory extends Converter.Factory {

    private final Gson gson;

    private CustomGsonConverterFactory(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        this.gson = gson;
    }

    public static CustomGsonConverterFactory create() {
        return create(new Gson());
    }

    public static CustomGsonConverterFactory create(Gson gson) {
        return new CustomGsonConverterFactory(gson);
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new CustomGsonResponseBodyConverter<>(gson, adapter);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new CustomGsonRequestBodyConverter<>(gson, adapter);
    }
}

實(shí)現(xiàn)Service的Java Admin API

添加Service實(shí)體

@Data @Builder
public class Service {

    private String id;
    private String name;
    private String protocol;
    private String host;
    private Integer port;
    private String path;
    private String url;
    private Integer retries;
    @SerializedName("connect_timeout")
    private Long connectTimeout;
    @SerializedName("read_timeout")
    private Long readTimeout;
    @SerializedName("write_timeout")
    private Long writeTimeout;
    @SerializedName("created_at")
    private Long createdAt;
    @SerializedName("updated_at")
    private Long updatedAt;
}

添加Service接口亚再,這里只要?jiǎng)h除和新增

public interface ServiceService {

    Service addService(Service service);
    void deleteService(String nameOrId);
}

添加Retrofit的處理接口

public interface RetrofitServiceService {

    @POST("services/")
    Call<Service> addService(@Body Service request);
    @DELETE("services/{nameOrId}")
    Call<Void> deleteService(@Path("nameOrId") String nameOrId);
}

實(shí)現(xiàn)Route的Java Admin API

添加Route實(shí)體

@Data @Builder
public class Route {

    private String id;
    private List<String> protocols;
    private List<String> methods;
    private List<String> hosts;
    private List<String> paths;
    @SerializedName("strip_path")
    private Boolean stripPath;
    @SerializedName("preserve_host")
    private Boolean preserveHost;
    private Service  service;
    @SerializedName("created_at")
    private Long createdAt;
    @SerializedName("updated_at")
    private Long updatedAt;
}

添加Route接口,這里只要?jiǎng)h除和新增

public interface RouteService {

    Route addRoute(Route route);
    void DeleteRoute(String id);
}

添加Retrofit的處理接口

public interface RetrofitRouteService {
    @POST("routes/")
    Call<Route> addRoute(@Body Route route);
    @DELETE("routes/{id}")
    Call<Void> DeleteRoute(@Path("id") String id);
}

單元測(cè)試一下

新建一個(gè)名字為example-service晨抡,地址為http://mockbin.org的Service氛悬。并為Service添加host為example.com的Route路由。

public class ServiceRouteTest extends BaseTest {

    public static final String EXAMPLE_SERVICE = "example-service";

    @Test
    public void createServiceAndRouteTest(){

        // 刪除Route和Service
        CommonList<Route> commonList = kongClient.getRouteService().listRoutesByService(EXAMPLE_SERVICE);
        List<Route> routeList = commonList.getData();
        if(null!=routeList && routeList.size()>0 ){
            for (Route route : routeList) {
                kongClient.getRouteService().DeleteRoute(route.getId());
            }
        }
        kongClient.getServiceService().deleteService(EXAMPLE_SERVICE);


        // 新建Service和Route
        Service service = Service.builder().url("http://mockbin.org").name(EXAMPLE_SERVICE).build();
        Service response4service = kongClient.getServiceService().addService(service);
        printJson(response4service);
        List<String> hostList = new ArrayList<>();
        hostList.add("example.com");
        Route route = Route.builder().hosts(hostList).service(Service.builder().id(response4service.getId()).build()).build();
        Route response4route = kongClient.getRouteService().addRoute(route);
        printJson(response4route);
    }

}

最后耘柱,檢查下效果

使用GET方法如捅,訪問(wèn)地址http://192.168.56.112:8000,并添加在頭部添加host[]=example.com调煎,結(jié)果如下:

使用Postman測(cè)試Kong

寫(xiě)在最后

  • 利用架子可以自定義其他Kong的JAVA客戶(hù)端镜遣。
  • 很多時(shí)候,我們的API地址是通過(guò)程序掃描出來(lái)的士袄,或者管理系統(tǒng)進(jìn)行配置的悲关。這個(gè)時(shí)候,我們就可以利用Kong的JAVA客戶(hù)端快速的實(shí)現(xiàn)Kong的接口管理娄柳,輪訓(xùn)等寓辱。
  • 應(yīng)用降級(jí)赤拒,流控秫筏,金絲雀诱鞠,灰度等等,都可以通過(guò)Kong的JAVA客戶(hù)端輕松實(shí)現(xiàn)跳昼。

穿梭機(jī):開(kāi)源API網(wǎng)關(guān)系統(tǒng)(Kong教程)入門(mén)到精通

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末般甲,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子鹅颊,更是在濱河造成了極大的恐慌敷存,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,188評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件堪伍,死亡現(xiàn)場(chǎng)離奇詭異锚烦,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)帝雇,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)涮俄,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人尸闸,你說(shuō)我怎么就攤上這事彻亲。” “怎么了吮廉?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,562評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵苞尝,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我宦芦,道長(zhǎng)宙址,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,893評(píng)論 1 295
  • 正文 為了忘掉前任调卑,我火速辦了婚禮抡砂,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘恬涧。我一直安慰自己注益,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布溯捆。 她就那樣靜靜地躺著聊浅,像睡著了一般。 火紅的嫁衣襯著肌膚如雪现使。 梳的紋絲不亂的頭發(fā)上低匙,一...
    開(kāi)封第一講書(shū)人閱讀 51,708評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音碳锈,去河邊找鬼顽冶。 笑死,一個(gè)胖子當(dāng)著我的面吹牛售碳,可吹牛的內(nèi)容都是我干的强重。 我是一名探鬼主播绞呈,決...
    沈念sama閱讀 40,430評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼间景!你這毒婦竟也來(lái)了佃声?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,342評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤倘要,失蹤者是張志新(化名)和其女友劉穎圾亏,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體封拧,經(jīng)...
    沈念sama閱讀 45,801評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡志鹃,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了泽西。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片曹铃。...
    茶點(diǎn)故事閱讀 40,115評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖捧杉,靈堂內(nèi)的尸體忽然破棺而出陕见,到底是詐尸還是另有隱情,我是刑警寧澤味抖,帶...
    沈念sama閱讀 35,804評(píng)論 5 346
  • 正文 年R本政府宣布评甜,位于F島的核電站,受9級(jí)特大地震影響非竿,放射性物質(zhì)發(fā)生泄漏蜕着。R本人自食惡果不足惜谋竖,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評(píng)論 3 331
  • 文/蒙蒙 一红柱、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蓖乘,春花似錦锤悄、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,008評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至些侍,卻和暖如春隶症,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背岗宣。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,135評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工蚂会, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人耗式。 一個(gè)月前我還...
    沈念sama閱讀 48,365評(píng)論 3 373
  • 正文 我出身青樓胁住,卻偏偏與公主長(zhǎng)得像趁猴,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子彪见,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容