7bf40a7b93ebf449426e8f494bc38de290d65336
[msb/apigateway.git] / msb-core / apiroute / apiroute-service / src / main / java / org / openo / msb / wrapper / consul / cache / HealthCache.java
1 /**\r
2  * Copyright 2016 ZTE, Inc. and others.\r
3  *\r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 package org.openo.msb.wrapper.consul.cache;\r
18 \r
19 import java.math.BigInteger;\r
20 import java.util.List;\r
21 \r
22 import org.openo.msb.wrapper.consul.HealthClient;\r
23 import org.openo.msb.wrapper.consul.async.ConsulResponseCallback;\r
24 import org.openo.msb.wrapper.consul.model.health.ServiceHealth;\r
25 \r
26 import com.google.common.base.Function;\r
27 \r
28 public class HealthCache extends ConsulCache<String, ServiceHealth>{\r
29     \r
30     private  final String serviceName;\r
31 \r
32     private  HealthCache(Function<ServiceHealth, String> keyConversion,\r
33             ConsulCache.CallbackConsumer<ServiceHealth> callbackConsumer,String serviceName) {\r
34         super(keyConversion, callbackConsumer);\r
35         this.serviceName=serviceName;\r
36         // TODO Auto-generated constructor stub\r
37     }\r
38     \r
39     \r
40     public static HealthCache newCache(\r
41         final HealthClient healthClient,\r
42         final String serviceName,\r
43         final int watchSeconds){\r
44        Function<ServiceHealth,String> keyExtractor = new Function<ServiceHealth, String>() {\r
45            @Override\r
46            public String apply(ServiceHealth input) {\r
47                //return input.getKey().substring(rootPath.length() + 1);\r
48                return input.getService().getId();\r
49            }\r
50        };  \r
51        \r
52        final CallbackConsumer<ServiceHealth> callbackConsumer = new CallbackConsumer<ServiceHealth>() {\r
53            @Override\r
54            public void consume(BigInteger index, ConsulResponseCallback<List<ServiceHealth>> callback) {\r
55                healthClient.getHealthyServiceInstances(serviceName,  watchParams(index, watchSeconds),callback);\r
56            }\r
57        };\r
58        \r
59         \r
60        return new HealthCache(keyExtractor, callbackConsumer,serviceName);\r
61         \r
62         \r
63     }\r
64     \r
65     public String getServiceName(){\r
66         return this.serviceName;\r
67     }\r
68     \r
69 \r
70 }