public class BalanceManager extends Object
CLIENT_BALANCE_TABLE table.
Maintains elastic property to sync balance in between mysql and redis cluster.| Modifier and Type | Field and Description |
|---|---|
static String |
APPLICATION_NAME |
static String |
BALANCE_FIELD
Redis cluster balance field constant key.
|
static String |
BM_ID_FIELD |
static String |
CLIENT_BALANCE_TABLE
MySQL table name where balance information can be found
|
static double |
LEASE_CHUNK_STEP
Value to increase or decrease when adjusting lease chunk with demand
|
static int |
MAX_THREAD_COUNT |
static double |
MAXIMUM_LEASE_CHUNK
Maximum lease chunk Balance Manager tries to store locally from Redis for an account
when
LeaseDTO.getLease(double, LeaseResponse, boolean) is called |
static double |
MAXIMUM_LOCAL_BALANCE
Maximum amount of money which can stay in available local balance of
LeaseDTO. |
static double |
MINIMUM_LEASE_CHUNK
Minimum lease chunk Balance Manager tries to store locally from Redis for an account
when
LeaseDTO.getLease(double, LeaseResponse, boolean) is called |
static long |
TIME_TO_DECREASE_LEASE_CHUNK
Time above which a lease request is received in Redis, we will decrease local balance chunk for a LeaseDTO
|
static long |
TIME_TO_INCREASE_LEASE_CHUNK
Time under which a lease request is received in Redis, we will increase local balance chunk for a LeaseDTO
|
static String |
TOKENIZER |
static String |
VERSION |
static long |
WAIT_TIME_BEFORE_FULL_RELEASE
When a 100% (full) balance return request is made for an account, Balance manager will not process
any further full amount return request for this time
|
| Constructor and Description |
|---|
BalanceManager(String identifier,
com.reve.redis.cluster.ClusterObserver clusterObserver)
Create an instance of
BalanceManager. |
BalanceManager(String identifier,
String redisHost,
int redisPort,
String redisPass,
com.reve.websocket.ssl.SSLConfiguration sslConfiguration)
Create an instance of
BalanceManager. |
BalanceManager(String identifier,
String redisHost,
int redisPort,
String redisPass,
com.reve.websocket.ssl.SSLConfiguration sslConfiguration,
int connectionCount)
Create an instance of
BalanceManager. |
| Modifier and Type | Method and Description |
|---|---|
void |
addOrgBilledAmount(long orgClientID,
double billedAmount)
Adds billed amount to total bill for corresponding account id
|
double |
addTerBilledAmount(long terClientID,
double billedAmount)
Adds billed amount to total billed amount for corresponding account id
|
Collection<Long> |
findTargetAccounts(String failedBMId)
Method to find the account IDs which were present in the failed SBC/Balance Manager
|
Set<Long> |
getAllAccountID()
Get the set of all account id present in this balance manager.
|
void |
getBalanceToSync(List<LeaseDTO> list,
boolean syncAll)
Get all the instances of
LeaseDTO those needed to be synced. |
com.reve.redis.cluster.ClusterObserver |
getClusterObserver()
Getter for
clusterObserver |
String |
getIdentifier() |
double |
getLease(long accountId,
double leaseAmount,
LeaseResponse response)
Try to get a lease from this account balance.
|
double |
getLease(long accountId,
double leaseAmount,
LeaseResponse response,
boolean partialEnabled)
Try to get a lease from this account balance.
|
LeaseDTO |
getLeaseDTO(long accountID)
Get the instance of
LeaseDTO mapped with the given account id. |
double |
getMysqlBalance(long accountId)
If the given accountId is not present in redis then it will be loaded from mysql database and be saved in redis
cluster.
|
double |
getPercentageToRelease() |
PubSubPublisher |
getPublisher()
Getter for
pubSubPublisher |
PubSubPublisher |
getPubSubPublisher() |
double |
getThresholdToReleaseFullAmount() |
boolean |
isFrozen(long accountID)
Check if the given account id is now in frozen mode or not.
|
void |
loadBalanceInRedis(long accountId)
Successful completion of this method will ensure the presence of this
LeaseDTO in redis
cluster Either in the nearest node or In the far node. |
boolean |
mitigatePossibleBalanceMismatch(long accountID)
This method will call balance mitigatory process to resolve any dispute in balance.
|
void |
onProcessShutdown(boolean returnBalance)
We have taken advanced amount from redis cluster, so
When system is getting shut down, all the available cached balance should be returned to redis,
otherwise some money will be lost.
|
void |
processAccFreezeAck(long accountID,
String balanceManagerID)
Process
MessageType.ACK_FREEZE_REQUEST message from the given balance manager. |
void |
processAccFreezeCompete(long accountID,
String balanceManagerID)
Process
MessageType.FREEZE_COMPLETE message from the given balance manager. |
void |
processAccFreezeRequest(long accountId)
When a freeze request is received from mitigator this method will be called.
|
void |
processAccUnFreezeCompete(long accountID,
String balanceManagerID)
Process
MessageType.UNFREEZE_COMPLETE message from the given balance manager. |
void |
processAccUnfreezeRequest(long accountId)
When an unfreeze request is received from mitigator this method will be called.
|
void |
refundBalance(long accountID,
double balance)
For some unsuccessful case we may need to refund the balance of a transaction.
|
double |
returnLease(long accountId,
double leaseAmount)
Extra amount left at the end of the call is added to the lease (make sure to provide +ve
value).
|
void |
returnLeaseOnRequest(long accountId,
boolean returnFullAmount)
In case the balance of an account gets exhausted, balance manager will broadcast an empty status to all BMs.
|
void |
saveRedisCall(RedisCallDTO redisCallDTO)
Whenever any redis call is required by
LeaseDTO asynchronously, this method must be called with an
instance of RedisCallDTO. |
boolean |
setBalance(long accountID,
double balance,
double credit)
Set the balance of the given account id to the given amount.
|
void |
setBalanceFreezer(BalanceFreezer balanceFreezer)
Setter for the balance freezer needed to freeze accounts
|
void |
setEnableRedisCall(boolean enableRedisCall) |
boolean |
setMysqlBalance(long accountId,
double balance,
double credit)
If the given accountId is not present in redis then it will be loaded from mysql database and be saved in redis
cluster.
|
void |
setPercentageToRelease(double percentageToRelease)
Setter for the percentage which Balance Manager will release when
returnLeaseOnRequest(long, boolean)
is called |
void |
setThresholdToReleaseFullAmount(double thresholdToReleaseFullAmount)
Setter to configure threshold under which Balance Manager will release the full available amount
|
void |
startMysqlBalanceUpdate(boolean start,
boolean redundancy)
If anyone wants
BalanceManager to update mysql balance as well, then this method must be called with true
By default BalanceManager will not update mysql balance. |
void |
syncAllAccounts(Collection<Long> accountsToSync)
Method to sync balance of the accounts present in failed SBC.
|
public static final String APPLICATION_NAME
public static final String VERSION
public static final String TOKENIZER
public static final String BM_ID_FIELD
public static final int MAX_THREAD_COUNT
public static final double MINIMUM_LEASE_CHUNK
LeaseDTO.getLease(double, LeaseResponse, boolean) is calledpublic static final double MAXIMUM_LEASE_CHUNK
LeaseDTO.getLease(double, LeaseResponse, boolean) is calledpublic static final double MAXIMUM_LOCAL_BALANCE
LeaseDTO. If available local
balance crosses this amount 50% of available amount will be returned to redis.public static final double LEASE_CHUNK_STEP
public static final long TIME_TO_INCREASE_LEASE_CHUNK
public static final long TIME_TO_DECREASE_LEASE_CHUNK
public static final long WAIT_TIME_BEFORE_FULL_RELEASE
public static final String CLIENT_BALANCE_TABLE
public static final String BALANCE_FIELD
public BalanceManager(String identifier, String redisHost, int redisPort, String redisPass, com.reve.websocket.ssl.SSLConfiguration sslConfiguration, int connectionCount) throws Exception
BalanceManager.identifier - Balance Manager unique identifier. Can not contain these characters in the string :
"-", "+", "*", ":", "\", "$", "%", "(", ")". Can not be null or empty.redisHost - Redis cluster server ip address where balance information will be cached. This cluster node
must be a master node in cluster.redisPort - Redis cluster server port where balance information will be cached.redisPass - Auth Password for redis clustersslConfiguration - if ssl/tls is configured in the redis cluster, then an instance of
SSLConfiguration must be passed, which will be used to connect to the redis
server. If ssl is not configured in the redis server, then this value should be nullconnectionCount - number of redis connection this application supposed to open.Exception - if occurs any while loading cluster information.public BalanceManager(String identifier, String redisHost, int redisPort, String redisPass, com.reve.websocket.ssl.SSLConfiguration sslConfiguration) throws Exception
BalanceManager.identifier - Balance Manager unique identifier. Can not contain these characters in the string :
"-", "+", "*", ":", "\", "$", "%", "(", ")". Can not be null or empty.redisHost - Redis cluster server ip address where balance information will be cached. This cluster node
must be a master node in cluster.redisPort - Redis cluster server port where balance information will be cached.redisPass - Auth Password for redis clustersslConfiguration - if ssl/tls is configured in the redis cluster, then an instance of
SSLConfiguration must be passed, which will be used to connect to the redis
server. If ssl is not configured in the redis server, then this value should be nullException - if occurs any while loading cluster information.public BalanceManager(String identifier, com.reve.redis.cluster.ClusterObserver clusterObserver) throws Exception
BalanceManager.identifier - Balance Manager unique identifier. Can not contain these characters in the string : "-", "+",
"*", ":", "\", "$", "%", "(", ")". Can not be null or empty.clusterObserver - Cluster Observer of which BalanceManager will be part of.Exception - if occurs any while loading cluster informationpublic PubSubPublisher getPublisher()
pubSubPublisherpubSubPublisherpublic double getMysqlBalance(long accountId)
accountId - Account ID for which balance information will be loaded into redis.public boolean setMysqlBalance(long accountId,
double balance,
double credit)
accountId - Account ID for which balance information will be loaded into redis.balance - Amount to be set in BALANCE_FIELD in CLIENT_BALANCE_TABLE tablecredit - Amount to be set in CREDIT_FIELD in CLIENT_BALANCE_TABLE tablepublic double getLease(long accountId,
double leaseAmount,
LeaseResponse response)
accountId - The account id lease needed fromleaseAmount - The amount to be added to the leaseresponse - The response value will be updated into this instance. This instance must be passed from the
caller, and values will be updated here.public double getLease(long accountId,
double leaseAmount,
LeaseResponse response,
boolean partialEnabled)
accountId - The account id lease needed fromleaseAmount - The amount to be added to the leaseresponse - The response value will be updated into this instance. This instance must be passed from the
caller, and values will be updated here.partialEnabled - if caller is happy with partial lease,
ex - caller requested for 10 dollar but leaseDTO gives only 5 dollar,
then this value must be truepublic double returnLease(long accountId,
double leaseAmount)
accountId - Account id the lease should be returned toleaseAmount - remaining lease amount. make sure that it's +vepublic boolean isFrozen(long accountID)
accountID - The account id which to be checked for frozen mode.public void refundBalance(long accountID,
double balance)
accountID - The account id for which refund should happenbalance - amount of balance should be refunded.public LeaseDTO getLeaseDTO(long accountID)
LeaseDTO mapped with the given account id. If there is none, then create one and
returnpublic void loadBalanceInRedis(long accountId)
LeaseDTO in redis
cluster Either in the nearest node or In the far node. If no one else has loaded the data, It
will load data from mysql and save it in My cluster Node
Which will be needed for all consecutive callaccountId - The account id of a client whose balance to be loaded into redis.public void returnLeaseOnRequest(long accountId,
boolean returnFullAmount)
accountId - For which account the balance is exhausted/empty.returnFullAmount - if this value is true, then it will return all available local balance to redis.public void processAccFreezeRequest(long accountId)
accountId - account id for which Freeze request is being processed.public void processAccUnfreezeRequest(long accountId)
accountId - the account id which needs to be unfrozenpublic void processAccFreezeAck(long accountID,
String balanceManagerID)
MessageType.ACK_FREEZE_REQUEST message from the given balance manager.accountID - Account id for which ack message is received.balanceManagerID - Identification of BalanceManager from where this message is received.public void processAccFreezeCompete(long accountID,
String balanceManagerID)
MessageType.FREEZE_COMPLETE message from the given balance manager.accountID - Account id for which MessageType.FREEZE_COMPLETE message is received.balanceManagerID - Identification of BalanceManager from where this message is received.public void processAccUnFreezeCompete(long accountID,
String balanceManagerID)
MessageType.UNFREEZE_COMPLETE message from the given balance manager.accountID - Account id for which MessageType.UNFREEZE_COMPLETE message is received.balanceManagerID - Identification of BalanceManager from where this message is received.public String getIdentifier()
public com.reve.redis.cluster.ClusterObserver getClusterObserver()
clusterObserverClusterObserver instance that was used to cache balance information.public double getThresholdToReleaseFullAmount()
public void setThresholdToReleaseFullAmount(double thresholdToReleaseFullAmount)
thresholdToReleaseFullAmount - Amount to set as threshold to release full amountpublic double getPercentageToRelease()
returnLeaseOnRequest(long, boolean) is calledpublic void setPercentageToRelease(double percentageToRelease)
returnLeaseOnRequest(long, boolean)
is calledpercentageToRelease - percentage tp release from available balancepublic PubSubPublisher getPubSubPublisher()
public void setBalanceFreezer(BalanceFreezer balanceFreezer)
balanceFreezer - Instance of balance freezer needed to freeze accountspublic void startMysqlBalanceUpdate(boolean start,
boolean redundancy)
BalanceManager to update mysql balance as well, then this method must be called with true
By default BalanceManager will not update mysql balance.start - if mysql balance update is required then true. Otherwise, false.redundancy - If redundancy is running for this BalanceManager then mysql balance update will be
as fast as possible, without any sleep. otherwise, mysql update will be periodical.public void addOrgBilledAmount(long orgClientID,
double billedAmount)
throws UnsupportedOperationException
orgClientID - originating client id for which bill should be addedbilledAmount - billed amount that should be addedUnsupportedOperationExceptionpublic double addTerBilledAmount(long terClientID,
double billedAmount)
throws UnsupportedOperationException
terClientID - terminating account id for which bill has happenedbilledAmount - billed amount that should be added in total billUnsupportedOperationExceptionpublic void getBalanceToSync(List<LeaseDTO> list, boolean syncAll)
LeaseDTO those needed to be synced.list - will contain those instances of LeaseDTOsyncAll - if we want all the instances, this value should be true.public Set<Long> getAllAccountID()
public boolean mitigatePossibleBalanceMismatch(long accountID)
accountID - The account id which need to be mitigated.public boolean setBalance(long accountID,
double balance,
double credit)
Channels.BALANCE_FREEZE_CHANNEL of the given account id.
2. Wait sometimes for everyone to respond.
3. Set the balance in mysql to the given amount.
4. Set the balance in redis to the given amount.
5. Send the account unfreeze request to Channels.BALANCE_FREEZE_CHANNEL of the given account id.accountID - the account ID for which balance to be set.balance - balance amount to be set.credit - credit amount to be set.public void syncAllAccounts(Collection<Long> accountsToSync) throws Exception
accountsToSync - Hashmap of the accounts that were present in the failed SBC and need to be syncedException - InterruptedException ExecutionExceptionpublic Collection<Long> findTargetAccounts(String failedBMId) throws Exception
failedBMId - Identifier of the SBC/ BalanceManager that failedException - InterruptedException ExecutionExceptionpublic void saveRedisCall(RedisCallDTO redisCallDTO)
LeaseDTO asynchronously, this method must be called with an
instance of RedisCallDTO. Which will be picked by an instance of RedisCaller and will be executedredisCallDTO - the instance of RedisCallDTO which should be executed by RedisCaller as soon as
possible.public void setEnableRedisCall(boolean enableRedisCall)
public void onProcessShutdown(boolean returnBalance)
returnBalance - If we want all the local balance to return in redis cluster then this value should be true,
otherwise this value should be false. If the application is running in standalone or running
as master this value should be true. It is considered that if the application is running in
redundancy mode only master should return balance in redis cluster and slave should not.Copyright © 2023. All rights reserved.