Monday, November 23, 2020

IBM Cloud VPC Network Load Balancer -- Java SDK Examples

 What is Network Load Balancer (NLB)?


Network Load Balancer works in Layer 4 and is best fit for business-critical and interactive workloads that require high throughput and low latency.

                -- from IBM Cloud blog

With traditional load balancer, all incoming and returning traffics would go through the load balancer itself. The big disadvantage is the high volume of traffics will increase the latency and affect the throughput.

NLB is using a technology called Direct Server Return (DSR). The information processed by the backend targets is sent directly back to the client, thus minimizing latency and optimizing throughput performance.

                  -- from IBM Cloud blog

Java SDK

This Java SDK is a new tool for developer to manage their IBM Cloud VPC resources. If you are new to Java and need to use the Java SDK to manage your NLB on IBM Cloud VPC, this doc can help you to get start. 

Import the VPC libaries:

import com.ibm.cloud.sdk.core.http.Response;
import com.ibm.cloud.sdk.core.http.ServiceCall;
import com.ibm.cloud.sdk.core.security.Authenticator;
import com.ibm.cloud.sdk.core.security.IamAuthenticator;
import com.ibm.cloud.is.vpc.v1.*;
import com.ibm.cloud.is.vpc.v1.model.*;
view raw gistfile1.txt hosted with ❤ by GitHub

Create VPC service object and authenticate:

// Define info.
String version = "2020-09-26";
// Create an IAM authenticator.
String apiKey = "<APIKEY>";
Authenticator authenticator = new IamAuthenticator(apiKey);
Vpc vpcService = new Vpc(version, Vpc.DEFAULT_SERVICE_NAME, authenticator);
vpcService.setServiceUrl(Vpc.DEFAULT_SERVICE_URL); // The DEFAULT_SERVICE_URL is https://us-south.iaas.cloud.ibm.com
view raw gistfile1.txt hosted with ❤ by GitHub

GET Profile:

// GET Profile (If you want to create Network Load Balancer, you need to sepcify the profile in your request. If not, an Application Load Balancer will be created. ) -----------------------------------------------------------------------------
public static void GetLoadBalancerProfile(Vpc vpcService, String name) throws Exception {
GetLoadBalancerProfileOptions getLbProfileOptions = new GetLoadBalancerProfileOptions.Builder(name).build();
Response<LoadBalancerProfile> lbProfile = vpcService.getLoadBalancerProfile(getLbProfileOptions).execute();
LoadBalancerProfile lbProfleObj = lbProfile.getResult();
String profleName = lbProfleObj.getName();
System.out.println(lbProfile.toString());
assertValueString(profleName, name);
}
view raw gistfile1.txt hosted with ❤ by GitHub

GET Load Balancer:

public static LoadBalancer GetLoadBalancer(Vpc vpcService, String lbId) throws Exception {
GetLoadBalancerOptions getLbOptions = new GetLoadBalancerOptions.Builder(lbId).build();
Response<LoadBalancer> lb = vpcService.getLoadBalancer(getLbOptions).execute();
LoadBalancer lbObj = lb.getResult();
String id = lbObj.getId();
assertValueString(id, lbId);
return lbObj;
}
view raw gistfile1.txt hosted with ❤ by GitHub

GET Load Balancer Listener:

public static void GetLoadBalancerListener(Vpc vpcService, String lbId, String id) throws Exception {
GetLoadBalancerListenerOptions getLbListenerOptions = new GetLoadBalancerListenerOptions.Builder()
.loadBalancerId(lbId)
.id(id)
.build();
Response<LoadBalancerListener> lbListener = vpcService.getLoadBalancerListener(getLbListenerOptions).execute();
LoadBalancerListener lbProfleObj = lbListener.getResult();
String listenerId = lbProfleObj.getId();
System.out.println(lbProfleObj.toString());
assertValueString(listenerId, id);
}
view raw gistfile1.txt hosted with ❤ by GitHub

GET Load Balancer Pool:

public static void GetLoadBalancerPool(Vpc vpcService, String lbId, String id) throws Exception {
GetLoadBalancerPoolOptions getLbPoolOptions = new GetLoadBalancerPoolOptions.Builder()
.loadBalancerId(lbId)
.id(id)
.build();
Response<LoadBalancerPool> lbPool = vpcService.getLoadBalancerPool(getLbPoolOptions).execute();
LoadBalancerPool lbPoolObj = lbPool.getResult();
String poolId = lbPoolObj.getId();
System.out.println(lbPoolObj.toString());
assertValueString(poolId, id);
}
view raw gistfile1.txt hosted with ❤ by GitHub

GET Load Balancer Pool Member:

public static void GetLoadBalancerPoolMember(Vpc vpcService, String lbId, String poolId, String id) throws Exception {
GetLoadBalancerPoolMemberOptions getMemberOptions = new GetLoadBalancerPoolMemberOptions.Builder()
.loadBalancerId(lbId)
.poolId(poolId)
.id(id)
.build();
Response<LoadBalancerPoolMember> member = vpcService.getLoadBalancerPoolMember(getMemberOptions).execute();
LoadBalancerPoolMember memberObj = member.getResult();
String memberId = memberObj.getId();
System.out.println(memberObj.toString());
assert memberId == id;
assertValueString(memberId, id);
}
view raw gistfile1.txt hosted with ❤ by GitHub

GET Load Balancer Statistics:

public static void GetLoadBalancerStatistics(Vpc vpcService, String id) throws Exception {
GetLoadBalancerStatisticsOptions getLbProfileOptions = new GetLoadBalancerStatisticsOptions.Builder(id).build();
Response<LoadBalancerStatistics> stat = vpcService.getLoadBalancerStatistics(getLbProfileOptions).execute();
LoadBalancerStatistics statObj = stat.getResult();
long activeConnections = statObj.getActiveConnections();
Float connectionRate = statObj.getConnectionRate();
long dataProcessed = statObj.getDataProcessedThisMonth();
Float throughtput = statObj.getThroughput();
System.out.println(statObj.toString());
assertValueLong(activeConnections, 0);
assert connectionRate >= 0;
assertValueLong(dataProcessed, 0);
assert throughtput >= 0;
}
view raw gistfile1.txt hosted with ❤ by GitHub

GET Load Balancer Statistics:

public static void GetLoadBalancerStatistics(Vpc vpcService, String id) throws Exception {
GetLoadBalancerStatisticsOptions getLbProfileOptions = new GetLoadBalancerStatisticsOptions.Builder(id).build();
Response<LoadBalancerStatistics> stat = vpcService.getLoadBalancerStatistics(getLbProfileOptions).execute();
LoadBalancerStatistics statObj = stat.getResult();
long activeConnections = statObj.getActiveConnections();
Float connectionRate = statObj.getConnectionRate();
long dataProcessed = statObj.getDataProcessedThisMonth();
Float throughtput = statObj.getThroughput();
System.out.println(statObj.toString());
assertValueLong(activeConnections, 0);
assert connectionRate >= 0;
assertValueLong(dataProcessed, 0);
assert throughtput >= 0;
}
view raw gistfile1.txt hosted with ❤ by GitHub

CREATE Load Balancer:

public static String CreateLoadBalancer(Vpc vpcService, String subnetId) throws Exception {
LocalDateTime dateObj = LocalDateTime.now();
DateTimeFormatter formatObj = DateTimeFormatter.ofPattern("yyMMddHHMM");
String formattedDate = dateObj.format(formatObj);
String lbName = "javasdk-nlb-" + formattedDate;
LoadBalancerProfileIdentity profile = new LoadBalancerProfileIdentityByName.Builder("network-fixed").build();
SubnetIdentityById subnet = new SubnetIdentityById.Builder(subnetId).build();
List<SubnetIdentity> subnets = new ArrayList<SubnetIdentity>();
subnets.add(subnet);
CreateLoadBalancerOptions createLbOptions = new CreateLoadBalancerOptions.Builder()
.name(lbName)
.isPublic(true)
.profile(profile)
.subnets(subnets)
.build();
Response<LoadBalancer> lb = vpcService.createLoadBalancer(createLbOptions).execute();
LoadBalancer lbObj = lb.getResult();
String lbId = lbObj.getId();
LoadBalancerProfileReference lbProfile = lbObj.getProfile();
boolean isPublic = lbObj.isIsPublic();
List<SubnetReference> lbSubnets = lbObj.getSubnets();
System.out.println(lbObj.toString());
assertValueString(lbProfile.getName(), "network-fixed");
assert isPublic == true;
assertValueString(lbSubnets.get(0).getId(), subnetId);
return lbId;
}
view raw gistfile1.txt hosted with ❤ by GitHub

CREATE Load Balancer Listener:

public static String CreateLoadBalancerListener(Vpc vpcService, String lbId) throws Exception {
long port = 8080;
CreateLoadBalancerListenerOptions createLbListenerOptions = new CreateLoadBalancerListenerOptions.Builder(lbId, port, "tcp").build();
Response<LoadBalancerListener> listener = vpcService.createLoadBalancerListener(createLbListenerOptions).execute();
LoadBalancerListener listenerObj = listener.getResult();
long ListenerPort = listenerObj.getPort();
String ListenerProtocol = listenerObj.getProtocol();
System.out.println(listenerObj.toString());
assertValueLong(ListenerPort, port);
assertValueString(ListenerProtocol, "tcp");
return listenerObj.getId();
}
view raw gistfile1.txt hosted with ❤ by GitHub

CREATE Load Balancer Pool:

public static String CreateLoadBalancerPool(Vpc vpcService, String lbId) throws Exception {
String algorithm = "weighted_round_robin";
String protocol = "tcp";
long port = 9090;
long delay = 10;
long maxRetries = 6;
long timeout = 5;
String type = "http";
LoadBalancerPoolHealthMonitorPrototype healthPrototype = new LoadBalancerPoolHealthMonitorPrototype.Builder(delay, maxRetries, timeout, type)
.port(port)
.build();
CreateLoadBalancerPoolOptions createLbPoolOptions = new CreateLoadBalancerPoolOptions.Builder(lbId, algorithm, protocol, healthPrototype).build();
Response<LoadBalancerPool> pool = vpcService.createLoadBalancerPool(createLbPoolOptions).execute();
LoadBalancerPool poolObj = pool.getResult();
String poolAlgorithm = poolObj.getAlgorithm();
String poolProtocol = poolObj.getProtocol();
LoadBalancerPoolHealthMonitor poolHealthMonitor = poolObj.getHealthMonitor();
System.out.println(poolObj.toString());
assertValueString(poolAlgorithm, algorithm);
assertValueString(poolProtocol, protocol);
assertValueLong(poolHealthMonitor.getDelay(), delay);
assertValueLong(poolHealthMonitor.getMaxRetries(), maxRetries);
assertValueLong(poolHealthMonitor.getPort(), port);
assertValueLong(poolHealthMonitor.getTimeout(), timeout);
assertValueString(poolHealthMonitor.getType(), type);
assertValueString(poolHealthMonitor.getUrlPath(), "/");
return poolObj.getId();
}
view raw gistfile1.txt hosted with ❤ by GitHub

CREATE Load Balancer Pool Member:

public static String CreateLoadBalancerPoolMember(Vpc vpcService, String lbId, String poolId, String instanceId) throws Exception {
long port = 80;
long weight = 60;
LoadBalancerPoolMemberTargetPrototypeInstanceIdentityInstanceIdentityById target;
target = new LoadBalancerPoolMemberTargetPrototypeInstanceIdentityInstanceIdentityById.Builder(instanceId).build();
CreateLoadBalancerPoolMemberOptions createLbPoolMemberOptions = new CreateLoadBalancerPoolMemberOptions.Builder(lbId, poolId, port, target)
.weight(weight)
.build();
Response<LoadBalancerPoolMember> lbPoolMember = vpcService.createLoadBalancerPoolMember(createLbPoolMemberOptions).execute();
LoadBalancerPoolMember memberObj = lbPoolMember.getResult();
long memberPort = memberObj.getPort();
long memberWeight = memberObj.getWeight();
String memberInstanceId = memberObj.getTarget().getId();
System.out.println(memberObj.toString());
assertValueLong(memberPort, port);
assertValueLong(memberWeight, weight);
assertValueString(memberInstanceId, instanceId);
return memberObj.getId();
}
view raw gistfile1.txt hosted with ❤ by GitHub

CREATE Load Balancer Listener With Pool:

public static String CreateLoadBalancerListenerWithPool(Vpc vpcService, String lbId, String poolId) throws Exception {
long port = 5050;
String protocol = "tcp";
LoadBalancerPoolIdentityById poolIdentity = new LoadBalancerPoolIdentityById.Builder(poolId).build();
CreateLoadBalancerListenerOptions createLbListenerOptions = new CreateLoadBalancerListenerOptions.Builder(lbId, port, "tcp")
.loadBalancerId(lbId)
.port(port)
.protocol(protocol)
.defaultPool(poolIdentity)
.build();
Response<LoadBalancerListener> listener = vpcService.createLoadBalancerListener(createLbListenerOptions).execute();
LoadBalancerListener listenerObj = listener.getResult();
long ListenerPort = listenerObj.getPort();
String listenerProtocol = listenerObj.getProtocol();
LoadBalancerPoolReference listenerPool = listenerObj.getDefaultPool();
System.out.println(listenerObj.toString());
assertValueLong(ListenerPort, port);
assertValueString(listenerProtocol, "tcp");
assertValueString(listenerPool.getId(), poolId);
return listenerObj.getId();
}
view raw gistfile1.txt hosted with ❤ by GitHub

CREATE Load Balancer Pool With Member:

public static String CreateLoadBalancerPoolWithMember(Vpc vpcService, String lbId, String instanceId) throws Exception {
String algorithm = "round_robin";
String protocol = "tcp";
long port = 6060;
long delay = 15;
long maxRetries = 10;
long timeout = 10;
String type = "tcp";
LoadBalancerPoolHealthMonitorPrototype healthPrototype = new LoadBalancerPoolHealthMonitorPrototype.Builder(delay, maxRetries, timeout, type)
.port(port)
.build();
LoadBalancerPoolMemberTargetPrototypeInstanceIdentityInstanceIdentityById target;
target = new LoadBalancerPoolMemberTargetPrototypeInstanceIdentityInstanceIdentityById.Builder(instanceId).build();
LoadBalancerPoolMemberPrototype memeberPrototype = new LoadBalancerPoolMemberPrototype.Builder(port, target).build();
CreateLoadBalancerPoolOptions createLbPoolOptions = new CreateLoadBalancerPoolOptions.Builder()
.loadBalancerId(lbId)
.algorithm(algorithm)
.protocol(protocol)
.healthMonitor(healthPrototype)
.addMembers(memeberPrototype)
.build();
Response<LoadBalancerPool> pool = vpcService.createLoadBalancerPool(createLbPoolOptions).execute();
LoadBalancerPool poolObj = pool.getResult();
String poolAlgorithm = poolObj.getAlgorithm();
String poolProtocol = poolObj.getProtocol();
LoadBalancerPoolHealthMonitor poolHealthMonitor = poolObj.getHealthMonitor();
List<LoadBalancerPoolMemberReference> members = poolObj.getMembers();
System.out.println(poolObj.toString());
assertValueString(poolAlgorithm, algorithm);
assertValueString(poolProtocol, protocol);
assertValueLong(poolHealthMonitor.getDelay(), delay);
assertValueLong(poolHealthMonitor.getMaxRetries(), maxRetries);
assertValueLong(poolHealthMonitor.getPort(), port);
assertValueLong(poolHealthMonitor.getTimeout(), timeout);
assertValueString(poolHealthMonitor.getType(), type);
if (members.get(0) == null) {
throw new Exception("Memeber not found");
}
return poolObj.getId();
}
view raw gistfile1.txt hosted with ❤ by GitHub

UPDATE Load Balancer:

public static void UpdateLoadBalancer(Vpc vpcService, String lbId) throws Exception {
LocalDateTime dateObj = LocalDateTime.now();
DateTimeFormatter formatObj = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
String formattedDate = dateObj.format(formatObj);
String newName = "javasdk-nlb-" + formattedDate;
UpdateLoadBalancerOptions updateLbOptions = new UpdateLoadBalancerOptions.Builder()
.id(lbId)
.name(newName)
.build();
Response<LoadBalancer> lb = vpcService.updateLoadBalancer(updateLbOptions).execute();
LoadBalancer lbObj = lb.getResult();
String lbName = lbObj.getName();
System.out.println(lbObj.toString());
assertValueString(lbName, newName);
}
view raw gistfile1.txt hosted with ❤ by GitHub

UPDATE Load Balancer Listener:

public static void UpdateLoadBalancerListener(Vpc vpcService, String lbId, String listenerId, String poolId) throws Exception {
long newPort = 8090;
LoadBalancerPoolIdentityById poolIdentitybyId = new LoadBalancerPoolIdentityById.Builder(poolId).build();
UpdateLoadBalancerListenerOptions updateLbListenerOptions = new UpdateLoadBalancerListenerOptions.Builder()
.loadBalancerId(lbId)
.id(listenerId)
.defaultPool(poolIdentitybyId)
.port(newPort)
.build();
Response<LoadBalancerListener> lbListener = vpcService.updateLoadBalancerListener(updateLbListenerOptions).execute();
LoadBalancerListener lbListenerObj = lbListener.getResult();
long listenerPort = lbListenerObj.getPort();
LoadBalancerPoolReference listenerPool = lbListenerObj.getDefaultPool();
System.out.println(lbListenerObj.toString());
assertValueLong(listenerPort, newPort);
assertValueString(listenerPool.getId(), poolId);
}
view raw gistfile1.txt hosted with ❤ by GitHub

UPDATE Load Balancer Pool:

public static void UpdateLoadBalancerPool(Vpc vpcService, String lbId, String poolId) throws Exception {
String newName = "new-pool";
String newAlgorithm = "least_connections";
long delay = 15;
long maxRetries = 6;
long timeout = 10;
String type = "tcp";
LoadBalancerPoolSessionPersistencePatch sessionPersistence = new LoadBalancerPoolSessionPersistencePatch.Builder("source_ip").build();
LoadBalancerPoolHealthMonitorPatch healthMonitor = new LoadBalancerPoolHealthMonitorPatch.Builder(delay, maxRetries, timeout, type).build();
UpdateLoadBalancerPoolOptions updateLbPoolOptions = new UpdateLoadBalancerPoolOptions.Builder()
.loadBalancerId(lbId)
.id(poolId)
.name(newName)
.sessionPersistence(sessionPersistence)
.algorithm(newAlgorithm)
.healthMonitor(healthMonitor)
.build();
Response<LoadBalancerPool> lbPool = vpcService.updateLoadBalancerPool(updateLbPoolOptions).execute();
LoadBalancerPool poolObj = lbPool.getResult();
String poolName = poolObj.getName();
String poolAlgorithm = poolObj.getAlgorithm();
LoadBalancerPoolHealthMonitor poolHealthMonitor = poolObj.getHealthMonitor();
System.out.println(poolObj.toString());
assertValueString(poolName, newName);
assertValueString(poolAlgorithm, newAlgorithm);
assertValueLong(poolHealthMonitor.getDelay(), delay);
assertValueLong(poolHealthMonitor.getMaxRetries(), maxRetries);
assertValueLong(poolHealthMonitor.getTimeout(), timeout);
assertValueString(poolHealthMonitor.getType(), type);
}
view raw gistfile1.txt hosted with ❤ by GitHub

UPDATE Load Balancer Member:

public static void UpdateLoadBalancerMember(Vpc vpcService, String lbId, String poolId, String memberId, String instanceId) throws Exception {
long newPort = 7070;
long newWeight = 90;
LoadBalancerPoolMemberTargetPrototypeInstanceIdentityInstanceIdentityById target;
target = new LoadBalancerPoolMemberTargetPrototypeInstanceIdentityInstanceIdentityById.Builder(instanceId).build();
UpdateLoadBalancerPoolMemberOptions updateLbPoolMemberOptions;
updateLbPoolMemberOptions = new UpdateLoadBalancerPoolMemberOptions.Builder()
.id(memberId)
.poolId(poolId)
.loadBalancerId(lbId)
.port(newPort)
.weight(newWeight)
.target(target)
.build();
Response<LoadBalancerPoolMember> lbMember = vpcService.updateLoadBalancerPoolMember(updateLbPoolMemberOptions).execute();
LoadBalancerPoolMember memberObj = lbMember.getResult();
long memberPort = memberObj.getPort();
long memberWeight = memberObj.getWeight();
String memberInstanceId = memberObj.getTarget().getId();
System.out.println(memberObj.toString());
assertValueLong(memberPort, newPort);
assertValueLong(memberWeight, newWeight);
assertValueString(memberInstanceId, instanceId);
}
view raw gistfile1.txt hosted with ❤ by GitHub

PUT Application LoadBalancer Member:

public static void PutApplicationLoadBalancerMember(Vpc vpcService, String lbId, String poolId, String instanceIp1, String instanceIp2) throws Exception {
long port1 = 2020;
LoadBalancerPoolMemberTargetPrototypeIP target1;
target1 = new LoadBalancerPoolMemberTargetPrototypeIP.Builder(instanceIp1).build();
LoadBalancerPoolMemberPrototype memeberPrototype1 = new LoadBalancerPoolMemberPrototype.Builder(port1, target1).build();
long port2 = 2020;
LoadBalancerPoolMemberTargetPrototypeIP target2;
target2 = new LoadBalancerPoolMemberTargetPrototypeIP.Builder(instanceIp2).build();
LoadBalancerPoolMemberPrototype memeberPrototype2 = new LoadBalancerPoolMemberPrototype.Builder(port2, target2).build();
List<LoadBalancerPoolMemberPrototype> members = new ArrayList();
members.add(memeberPrototype1);
members.add(memeberPrototype2);
ReplaceLoadBalancerPoolMembersOptions putLbMemberOptions = new ReplaceLoadBalancerPoolMembersOptions.Builder()
.loadBalancerId(lbId)
.poolId(poolId)
.members(members)
.build();
Response<LoadBalancerPoolMemberCollection> response = vpcService.replaceLoadBalancerPoolMembers(putLbMemberOptions).execute();
System.out.println(response.toString());
System.out.print(response.getStatusCode());
}
view raw gistfile1.txt hosted with ❤ by GitHub

DELETE Load Balancer:

public static void DeleteLoadBalancer(Vpc vpcService, String lbId) throws Exception {
DeleteLoadBalancerOptions deleteLbOptions = new DeleteLoadBalancerOptions.Builder(lbId).build();
Response<Void> response = vpcService.deleteLoadBalancer(deleteLbOptions).execute();
if (response.getStatusCode() != 204) {
throw new Exception();
}
}
view raw gistfile1.txt hosted with ❤ by GitHub

DELETE Load Balancer Listener:

public static void DeleteLoadBalancerListener(Vpc vpcService, String lbId, String listenerId) throws Exception {
DeleteLoadBalancerListenerOptions deleteLbListenerOptions = new DeleteLoadBalancerListenerOptions.Builder(lbId, listenerId).build();
Response<Void> response = vpcService.deleteLoadBalancerListener(deleteLbListenerOptions).execute();
if (response.getStatusCode() != 204) {
throw new Exception();
}
}
view raw gistfile1.txt hosted with ❤ by GitHub

DELETE Load Balancer Pool:

public static void DeleteLoadBalancerPool(Vpc vpcService, String lbId, String poolId) throws Exception {
DeleteLoadBalancerPoolOptions deleteLbPoolOptions = new DeleteLoadBalancerPoolOptions.Builder(lbId, poolId).build();
Response<Void> response = vpcService.deleteLoadBalancerPool(deleteLbPoolOptions).execute();
if (response.getStatusCode() != 204) {
throw new Exception();
}
}
view raw gistfile1.txt hosted with ❤ by GitHub

DELETE Load Balancer Pool Member:

public static void DeleteLoadBalancerPoolMember(Vpc vpcService, String lbId, String poolId, String memberId) throws Exception {
DeleteLoadBalancerPoolMemberOptions deleteLbPoolMemberOptions = new DeleteLoadBalancerPoolMemberOptions.Builder(lbId, poolId, memberId).build();
Response<Void> response = vpcService.deleteLoadBalancerPoolMember(deleteLbPoolMemberOptions).execute();
if (response.getStatusCode() != 204) {
throw new Exception();
}
}
view raw gistfile1.txt hosted with ❤ by GitHub


Some references:

Java SDK version: https://mvnrepository.com/artifact/com.ibm.cloud/vpc
Doc: https://ibm.github.io/vpc-java-sdk/docs/latest/
Source: https://github.com/IBM/vpc-java-sdk


IBM Cloud VPC Network Load Balancer -- Node.js SDK Examples

 What is Network Load Balancer (NLB)? Network Load Balancer works in Layer 4 and is best fit for business-critical and intera...