use of com.tencent.polaris.api.exception.PolarisException in project polaris-java by polarismesh.
the class HttpHealthChecker method detectInstance.
@Override
public DetectResult detectInstance(Instance instance) throws PolarisException {
try {
// TODO 从配置读取
String pattern = "/detect";
String path = String.format("http://%s:%d%s", instance.getHost(), instance.getPort(), pattern);
java.net.URL url = new java.net.URL(path);
java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// 连接超时
conn.setConnectTimeout(3 * 1000);
// 读取超时
conn.setReadTimeout(3 * 1000);
if (conn.getResponseCode() == EXPECT_CODE) {
return new DetectResult(RetStatus.RetSuccess);
}
return new DetectResult(RetStatus.RetFail);
} catch (Exception e) {
LOG.error("http detect exception, service:{}, host:{}, port:{}, e:{}", instance.getService(), instance.getHost(), instance.getPort(), e);
return new DetectResult(RetStatus.RetFail);
}
}
use of com.tencent.polaris.api.exception.PolarisException in project polaris-java by polarismesh.
the class UdpHealthChecker method detectInstance.
@Override
public DetectResult detectInstance(Instance instance) throws PolarisException {
DatagramSocket socket = null;
try {
// TODO 从配置中读取
String sendStr = "detect";
InetAddress inet = InetAddress.getByName(instance.getHost());
byte[] sendBytes = sendStr.getBytes("UTF8");
socket = new DatagramSocket();
// 两秒接收不到数据认为超时,防止获取不到连接一直在receive阻塞
socket.setSoTimeout(2000);
// 发送数据
DatagramPacket sendPacket = new DatagramPacket(sendBytes, sendBytes.length, inet, instance.getPort());
socket.send(sendPacket);
byte[] recvBuf = new byte[1024];
DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
socket.receive(recvPacket);
socket.close();
String expectRecvStr = "ok";
byte[] expectRecvBytes = expectRecvStr.getBytes("UTF8");
if (!Arrays.equals(Arrays.copyOfRange(recvBuf, 0, expectRecvBytes.length), expectRecvBytes)) {
return new DetectResult(RetStatus.RetFail);
}
return new DetectResult(RetStatus.RetSuccess);
} catch (Exception e) {
LOG.error("udp detect instance exception, host:{}, port:{}, e:{}", instance.getHost(), instance.getPort(), e);
return null;
} finally {
if (socket != null) {
socket.close();
}
}
}
use of com.tencent.polaris.api.exception.PolarisException in project polaris-java by polarismesh.
the class WeightedRandomBalance method chooseInstance.
@Override
public Instance chooseInstance(Criteria criteria, ServiceInstances svcInstances) throws PolarisException {
int totalWeight = svcInstances.getTotalWeight();
if (totalWeight <= 0) {
totalWeight = sumTotalWeight(svcInstances);
}
if (totalWeight == 0) {
throw new PolarisException(ErrorCode.INSTANCE_NOT_FOUND, String.format("all instances weight 0 for %s:%s", svcInstances.getNamespace(), svcInstances.getService()));
}
// 进行权重区间分配
List<Instance> instances = svcInstances.getInstances();
int randomValue = Math.abs(random.nextInt() % totalWeight);
int start = 0;
int end = 0;
for (Instance instance : instances) {
end = end + instance.getWeight();
if (randomValue >= start && randomValue < end) {
return instance;
}
start = end;
}
// 全都分配不到,则随机获取一个
return instances.get(totalWeight % instances.size());
}
use of com.tencent.polaris.api.exception.PolarisException in project polaris-java by polarismesh.
the class ConsecutiveCircuitBreaker method init.
@Override
public void init(InitContext ctx) throws PolarisException {
CircuitBreakerConfig circuitBreakerConfig = ctx.getConfig().getConsumer().getCircuitBreaker();
OutlierDetectionConfig outlierDetection = ctx.getConfig().getConsumer().getOutlierDetection();
HalfOpenConfig halfOpenConfig = new HalfOpenConfig(circuitBreakerConfig, outlierDetection);
Config cfg = circuitBreakerConfig.getPluginConfig(getName(), Config.class);
if (cfg == null) {
throw new PolarisException(ErrorCode.INVALID_CONFIG, String.format("plugin %s config is missing", getName()));
}
ConfigSet<Config> configSet = new ConfigSet<>(StatusDimension.Level.SERVICE, false, halfOpenConfig, cfg);
configGroup = new ConfigGroup<>(configSet);
stateMachine = new StateMachineImpl(configGroup, id, this);
flowControlParam = new DefaultFlowControlParam(ctx.getConfig().getGlobal().getAPI());
}
use of com.tencent.polaris.api.exception.PolarisException in project polaris-java by polarismesh.
the class MetadataRouterTest method testFailoverNoneScene.
@Test
public void testFailoverNoneScene() {
Configuration configuration = TestUtils.configWithEnvAddress();
try (ConsumerAPI consumer = DiscoveryAPIFactory.createConsumerAPIByConfig(configuration)) {
// 该服务下有四个实例,只有一个80端口实例满足metadata路由,但是不健康,降级策略采用默认不降级
for (int i = 0; i < 10; i++) {
GetOneInstanceRequest getInstances2 = new GetOneInstanceRequest();
getInstances2.setNamespace(NAMESPACE_PRODUCTION);
getInstances2.setService(METADATA_SERVICE);
Map<String, String> map = new HashMap<>();
map.put("Env-set", "1-1");
getInstances2.setMetadata(map);
InstancesResponse ins = null;
try {
ins = consumer.getOneInstance(getInstances2);
} catch (PolarisException e) {
Assert.assertEquals(ErrorCode.METADATA_MISMATCH, e.getCode());
}
}
}
}
Aggregations