. net client
Test code example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.Redis;
namespace ServiceStack.Redis.Tests
{
class Program
{
public static void RedisClientTest()
{
string host = "127.0.0.1";/*Access host address*/
string password = "password";/*Password*/
RedisClient redisClient = new RedisClient(host, 6379, password);
string key = "test-aliyun";
string value = "test-aliyun-value";
redisClient.Set(key, value);
string listKey = "test-aliyun-list";
System.Console.WriteLine("set key " + key + " value " + value);
string getValue = System.Text.Encoding.Default.GetString(redisClient.Get(key));
System.Console.WriteLine("get key " + getValue);
System.Console.Read();
}
public static void RedisPoolClientTest()
{
string[] testReadWriteHosts = new[] {
"redis://password@127.0.0.1:6379"/*redis://Password@Access Address: Port*/
};
RedisConfig.VerifyMasterConnections = false;//Need to set up
PooledRedisClientManager redisPoolManager = new PooledRedisClientManager(10/*Number of connection pools*/, 10/*Connection pool timeout*/, testReadWriteHosts);
for (int i = 0; i < 100; i++)
{
IRedisClient redisClient = redisPoolManager.GetClient();//Get connection
RedisNativeClient redisNativeClient = (RedisNativeClient)redisClient;
redisNativeClient.Client = null;//ApsaraDB for Redis does not support client setname, so the client object needs to be null as shown here
try
{
string key = "test-aliyun1111";
string value = "test-aliyun-value1111";
redisClient.Set(key, value);
string listKey = "test-aliyun-list";
redisClient.AddItemToList(listKey, value);
System.Console.WriteLine("set key " + key + " value " + value);
string getValue = redisClient.GetValue(key);
System.Console.WriteLine("get key " + getValue);
redisClient.Dispose();//
}
catch (Exception e)
{
System.Console.WriteLine(e.Message);
}
}
System.Console.Read();
}
static void Main(string[] args)
{
//Single link mode
RedisClientTest();
//Connection pool mode
RedisPoolClientTest();
}
}
}
Best practices
1. Player List
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;
public class GameRankSample {
static int TOTAL_SIZE = 20;
public static void main(String[] args)
{
//Connection information, available from the console
String host = "xxxxxxxxxx.m.cnhz1.kvstore.aliyuncs.com";
int port = 6379;
Jedis jedis = new Jedis(host, port);
try {
//Instance password
String authString = jedis.auth("password");//password
if (!authString.equals("OK"))
{
System.err.println("AUTH Failed: " + authString);
return;
}
//Key (key)
String key = "Game Name: Run, Ali!";
//Clear up possible existing data
jedis.del(key);
//Simulate the generation of several gamers
List<String> playerList = new ArrayList<String>();
for (int i = 0; i < TOTAL_SIZE; ++i)
{
//Random generation of each player's ID
playerList.add(UUID.randomUUID().toString());
}
System.out.println("Enter all players ");
//Record each player's score
for (int i = 0; i < playerList.size(); i++)
{
//Random generation of numbers to simulate players'game scores
int score = (int)(Math.random()*5000);
String member = playerList.get(i);
System.out.println("Game player ID: " + member + ", Player score: " + score);
//Add the player's ID and score to the SortedSet corresponding to the key.
jedis.zadd(key, score, member);
}
//Print out all player rankings
System.out.println();
System.out.println(" "+key);
System.out.println(" Player List ");
//Get an ordered list of players from the SortedSet for the corresponding key
Set<Tuple> scoreList = jedis.zrevrangeWithScores(key, 0, -1);
for (Tuple item : scoreList) {
System.out.println("Game player ID: "+item.getElement()+", Player score:"+Double.valueOf(item.getScore()).intValue());
}
//Output Print Top5 Player List
System.out.println();
System.out.println(" "+key);
System.out.println(" Top Game player");
scoreList = jedis.zrevrangeWithScores(key, 0, 4);
for (Tuple item : scoreList) {
System.out.println("Game player ID: "+item.getElement()+", Player score:"+Double.valueOf(item.getScore()).intValue());
}
//Output Print List of Specific Players
System.out.println();
System.out.println(" "+key);
System.out.println(" Players with points between 1000 and 2000");
//Get the integral from the SortedSet of the corresponding key1000to2000Player List of ___________
scoreList = jedis.zrangeByScoreWithScores(key, 1000, 2000);
for (Tuple item : scoreList) {
System.out.println("Game player ID: "+item.getElement()+", Player score:"+Double.valueOf(item.getScore()).intValue());
}
} catch (Exception e) {
e.printStackTrace();
}finally{
jedis.quit();
jedis.close();
}
}
}
Operation result
Enter all players Player ID: 9193e26f-6a71-4c76-8666-eaf8ee97ac86, player score: 3860 Player ID: db03520b-75a3-48e5-850a-071722ff7afb, player score: 4853 Player ID: d302d24d-d380-4e15-a4d6-84f71313f27a, player score: 2931 Player ID: bee46f9d-4b05-425e-8451-8aa6d 48858e6, player score: 1796 Player ID: ec24fb9e-366e-4b89-a0d5-0be151a8cad0, player score: 2263 Player ID: e11ecc2c-cd51-4339-8412-c711142ca7aa, player score: 1848 Player ID: 4c396f67-da7c-4b99-a783-25919d52d756, player score: 958 Player ID: a6299dd2-4f38-4528-bb5a-aa2d48a9f94a, player score: 2428 Player ID: 2e4ec631-1e4e-4ef0-914f-7bf1745f7d65, player score: 4478 Player ID: 24235a85-85b9-476e-8b96-39f294f57aa7, player score: 1655 Player ID: e3e8e1fa-6aac-4a0c-af80-4c4a1e126cd1, player score: 4064 Player ID: 99bc5b4f-e32a-4295-bc3a-0324887bb77e, player score: 4852 Player ID: 19e2aa6b-a2d8-4e56-bdf7-8b59f64bd8e0, player score: 3394 Player ID: cb62bb24-1318-4af2-9d9b-fbff 7280dbec, player score: 3405 Player ID: ec0f06da-91ee-447b-b935-7ca935dc7968, player score: 4391 Player ID: 2c814a6f-3706-4280-9085-5fe5fd56b71c, player score: 2510 Player ID: 9ee2ed6d-08b8-4e7f-b52c-9adfe1e32dda, player score: 63 Player ID: 0293b43a-1554-4157-a95b-b78de9edf6dd, player score: 1008 Player ID: 674 bbdd1-2023-46ae-bbe6-dfcd8e372430, player score: 2265 Player ID: 34574e3e-9cc5-43ed-ba15-9f5405312692, player score: 3734 Game Name: Run, Ali! Player List Player ID: db03520b-75a3-48e5-850a-071722ff7afb, player score: 4853 Player ID: 99bc5b4f-e32a-4295-bc3a-0324887bb77e, player score: 4852 Player ID: 2e4ec631-1e4e-4ef0-914f-7bf1745f7d65, player score: 4478 Player ID: ec0f06da-91ee-447b-b935-7ca935dc7968, player score: 4391 Player ID: e3e8e1fa-6aac-4a0c-af80-4c4a1e126cd1, player score: 4064 Player ID: 9193e26f-6a71-4c76-8666-eaf8ee97ac86, player score: 3860 Player ID: 34574e3e-9cc5-43ed-ba15-9f5405312692, player score: 3734 Player ID: cb62bb24-1318-4af2-9d9b-fbff 7280 dbec, player score: 3405 Player ID: 19e2aa6b-a2d8-4e56-bdf7-8b59f64bd8e0, player score: 3394 Player ID: d302d24d-d380-4e15-a4d6-84f71313f27a, player score: 2931 Player ID: 2c814a6f-3706-4280-9085-5fe5fd56b71c, player score: 2510 Player ID: a6299dd2-4f38-4528-bb5a-aa2d48a9f94a, player score: 2428 Player ID: 674 bbdd1-2023-46ae-bbe6-dfcd8e372430, player score: 2265 Player ID: ec24fb9e-366e-4b89-a0d5-0be151a8cad0, player score: 2263 Player ID: e11ecc2c-cd51-4339-8412-c711142ca7aa, player score: 1848 Player ID: bee46f9d-4b05-425e-8451-8aa6d 48858e6, player score: 1796 Player ID: 24235a85-85b9-476e-8b96-39f294f57aa7, player score: 1655 Player ID: 0293b43a-1554-4157-a95b-b78de9edf6dd, player score: 1008 Player ID: 4c396f67-da7c-4b99-a783-25919d52d756, player score: 958 Player ID: 9ee2ed6d-08b8-4e7f-b52c-9adfe1e32dda, player score: 63 Game Name: Run, Ali! Top player Player ID: db03520b-75a3-48e5-850a-071722ff7afb, player score: 4853 Player ID: 99bc5b4f-e32a-4295-bc3a-0324887bb77e, player score: 4852 Player ID: 2e4ec631-1e4e-4ef0-914f-7bf1745f7d65, player score: 4478 Player ID: ec0f06da-91ee-447b-b935-7ca935dc7968, player score: 4391 Player ID: e3e8e1fa-6aac-4a0c-af80-4c4a1e126cd1, player score: 4064 Game Name: Run, Ali! Players with points between 1000 and 2000 Player ID: 0293b43a-1554-4157-a95b-b78de9edf6dd, player score: 1008 Player ID: 24235a85-85b9-476e-8b96-39f294f57aa7, player score: 1655 Player ID: bee46f9d-4b05-425e-8451-8aa6d 48858e6, player score: 1796 Player ID: e11ecc2c-cd51-4339-8412-c711142ca7aa, player score: 1848
2. Analysis of the Relevance of Commodities in Online Malls
Code example
package shop.kvstore.aliyun.com;
import java.util.Set;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;
public class AliyunShoppingMall {
public static void main(String[] args)
{
//ApsaraDB for Redis connection information is available from the console
String host = "xxxxxxxx.m.cnhza.kvstore.aliyuncs.com";
int port = 6379;
Jedis jedis = new Jedis(host, port);
try {
//Instance password for ApsaraDB for Redis
String authString = jedis.auth("password");//password
if (!authString.equals("OK"))
{
System.err.println("AUTH Failed: " + authString);
return;
}
//Product list
String key0="Ali cloud:product:Beer";
String key1="Ali cloud:product:Chocolates";
String key2="Ali cloud:product:cola";
String key3="Ali cloud:product:Chewing gum";
String key4="Ali cloud:product:Dried beef";
String key5="Ali cloud:product:Chicken wings";
final String[] aliyunProducts=new String[]{key0,key1,key2,key3,key4,key5};
//Initialization, clearing possible old data
for (int i = 0; i < aliyunProducts.length; i++) {
jedis.del(aliyunProducts[i]);
}
//Simulate user shopping
for (int i = 0; i < 5; i++) {//Simulate multiple user purchasing behavior
customersShopping(aliyunProducts,i,jedis);
}
System.out.println();
//Use ApsaraDB for Redis to export correlations between commodities
for (int i = 0; i < aliyunProducts.length; i++) {
System.out.println(">>>>>>>>>>and"+aliyunProducts[i]+"The products purchased together are<<<<<<<<<<<<<<<");
Set<Tuple> relatedList = jedis.zrevrangeWithScores(aliyunProducts[i], 0, -1);
for (Tuple item : relatedList) {
System.out.println("Commodity Name:"+item.getElement()+", Number of co-purchases:"+Double.valueOf(item.getScore()).intValue());
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
jedis.quit();
jedis.close();
}
}
private static void customersShopping(String[] products, int i, Jedis jedis) {
//Simply simulate three kinds of purchasing behavior, randomly select as the user's purchasing choice
int bought=(int)(Math.random()*3);
if(bought==1){
//Analog business logic: Users buy the following products
System.out.println("user"+i+"Bought"+products[0]+","+products[2]+","+products[1]);
//Record product-to-product associations in the PortSet of ApsaraDB for Redis
jedis.zincrby(products[0], 1, products[1]);
jedis.zincrby(products[0], 1, products[2]);
jedis.zincrby(products[1], 1, products[0]);
jedis.zincrby(products[1], 1, products[2]);
jedis.zincrby(products[2], 1, products[0]);
jedis.zincrby(products[2], 1, products[1]);
}else if(bought==2){
//Analog business logic: Users buy the following products
System.out.println("user"+i+"Bought"+products[4]+","+products[2]+","+products[3]);
//Record product-to-product associations in the PortSet of ApsaraDB for Redis
jedis.zincrby(products[4], 1, products[2]);
jedis.zincrby(products[4], 1, products[3]);
jedis.zincrby(products[3], 1, products[4]);
jedis.zincrby(products[3], 1, products[2]);
jedis.zincrby(products[2], 1, products[4]);
jedis.zincrby(products[2], 1, products[3]);
}else if(bought==0){
//Analog business logic: Users buy the following products
System.out.println("user"+i+"Bought"+products[1]+","+products[5]);
//Record product-to-product associations in the PortSet of ApsaraDB for Redis
jedis.zincrby(products[5], 1, products[1]);
jedis.zincrby(products[1], 1, products[5]);
}
}
}
Operation result
After entering the correct ApsaraDB for Redis instance access address and password, run the above Java program, and the output is as follows:
User 0 purchased Aliyun: Products: Chocolate, Aliyun: Products: Chicken Wings User 1 Purchased Aliyun: Products: Beef jerky, Aliyun: Products: Coke, Aliyun: Products: Chewing gum User 2 purchased Aliyun: Products: Beer, Aliyun: Products: Coke, Aliyun: Products: Chocolate User 3 purchased Aliyun: Products: Beef jerky, Aliyun: Products: Coke, Aliyun: Products: Chewing gum User 4 bought Aliyun: Products: Chocolate, Aliyun: Products: Chicken Wings With Aliyun: Products: Products purchased with beer are <<<<<<<<<<<<<<<<<<<<< << < < < Commodity Name: Aliyun: Products: Chocolate, the number of co-purchases: 1 Commodity Name: Aliyun: Products: Coke, the number of co-purchases: 1 With Aliyun: Products: Chocolate products purchased together are <<<<<<<<<<<<<<<<<<<<<< < < < < Commodity Name: Aliyun: Products: Chicken Wings, Joint Purchase Number: 2 Commodity Name: Aliyun: Products: Beer, the number of co-purchases: 1 Commodity Name: Aliyun: Products: Coke, the number of co-purchases: 1 With Aliyun: Products: The products that Coke was purchased together are <<<<<<<<<<<<<<<<<<<<< <<< < < < < Commodity Name: Aliyun: Product: Beef jerky, co-purchase times: 2 Commodity Name: Aliyun: Products: Chewing gum, co-purchase times: 2 Commodity Name: Aliyun: Products: Chocolate, the number of co-purchases: 1 Commodity Name: Aliyun: Products: Beer, the number of co-purchases: 1 With Aliyun: Products: The products purchased together with chewing gum are <<<<<<<<<<<<<<<<<<<<<<< < < < < < Commodity Name: Aliyun: Product: Beef jerky, co-purchase times: 2 Commodity Name: Aliyun: Product: Coke, co-purchase times: 2 With Aliyun: Products: The products purchased together with beef jerky are <<<<<<<<<<<<<<<<<<<< << < < < < Commodity Name: Aliyun: Product: Coke, co-purchase times: 2 Commodity Name: Aliyun: Products: Chewing gum, co-purchase times: 2 With Aliyun: Products: Products purchased with chicken wings are <<<<<<<<<<<<<<<<<<<<< <<< < < < Commodity Name: Aliyun: Products: Chocolate, the number of co-purchases: 2
Publication and Subscription of Messages
Code example
Publisher (publish client)
package message.kvstore.aliyun.com;
import redis.clients.jedis.Jedis;
public class KVStorePubClient {
private Jedis jedis;//
public KVStorePubClient(String host,int port, String password){
jedis = new Jedis(host,port);
//Example password for KVStore
String authString = jedis.auth(password);//password
if (!authString.equals("OK"))
{
System.err.println("AUTH Failed: " + authString);
return;
}
}
public void pub(String channel,String message){
System.out.println(" >>> Release(PUBLISH) > Channel:"+channel+" > Sent out Message:"+message);
jedis.publish(channel, message);
}
public void close(String channel){
System.out.println(" >>> Release(PUBLISH)End > Channel:"+channel+" > Message:quit");
//The message publisher ends sending a quit message.
jedis.publish(channel, "quit");
}
}
Message Subscriber (subscribe client)
package message.kvstore.aliyun.com;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
public class KVStoreSubClient extends Thread{
private Jedis jedis;
private String channel;
private JedisPubSub listener;
public KVStoreSubClient(String host,int port, String password){
jedis = new Jedis(host,port);
//Instance password for ApsaraDB for Redis
String authString = jedis.auth(password);//password
if (!authString.equals("OK"))
{
System.err.println("AUTH Failed: " + authString);
return;
}
}
public void setChannelAndListener(JedisPubSub listener,String channel){
this.listener=listener;
this.channel=channel;
}
private void subscribe(){
if(listener==null || channel==null){
System.err.println("Error:SubClient> listener or channel is null");
}
System.out.println(" >>> Subscribe(SUBSCRIBE) > Channel:"+channel);
System.out.println();
//When the recipient listens for subscription messages, the process will be blocked until quit messages (passive mode) are received, or the subscription will be cancelled actively.
jedis.subscribe(listener, channel);
}
public void unsubscribe(String channel){
System.out.println(" >>> unsubscribe(UNSUBSCRIBE) > Channel:"+channel);
System.out.println();
listener.unsubscribe(channel);
}
@Override
public void run() {
try{
System.out.println();
System.out.println("----------Subscribe SUBSCRIBE start-------");
subscribe();
System.out.println("----------Subscribe SUBSCRIBE End-------");
System.out.println();
}catch(Exception e){
e.printStackTrace();
}
}
}
message listener
package message.kvstore.aliyun.com;
import redis.clients.jedis.JedisPubSub;
public class KVStoreMessageListener extends JedisPubSub{
@Override
public void onMessage(String channel, String message) {
System.out.println(" <<< Subscribe(SUBSCRIBE)< Channel:" + channel + " >Received Message:" + message );
System.out.println();
//When the received message is quit, unsubscribe (passive mode)
if(message.equalsIgnoreCase("quit")){
this.unsubscribe(channel);
}
}
@Override
public void onPMessage(String pattern, String channel, String message) {
// TODO Auto-generated method stub
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
// TODO Auto-generated method stub
}
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
// TODO Auto-generated method stub
}
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
// TODO Auto-generated method stub
}
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
// TODO Auto-generated method stub
}
}
Sample main program
package message.kvstore.aliyun.com;
import java.util.UUID;
import redis.clients.jedis.JedisPubSub;
public class KVStorePubSubTest {
//ApsaraDB for Redis connection information is available from the console
static final String host = "xxxxxxxxxx.m.cnhza.kvstore.aliyuncs.com";
static final int port = 6379;
static final String password="password";//password
public static void main(String[] args) throws Exception{
KVStorePubClient pubClient = new KVStorePubClient(host, port,password);
final String channel = "KVStore channel-A";
//The sender starts sending the message, and nobody subscribes at this time, so the message will not be received.
pubClient.pub(channel, "Aliyun Message 1: (No one is subscribing at this time, so this message will not be received)");
//Message Receiver
KVStoreSubClient subClient = new KVStoreSubClient(host, port,password);
JedisPubSub listener = new KVStoreMessageListener();
subClient.setChannelAndListener(listener, channel);
//Message Receiver Begins Subscription
subClient.start();
//The sender continues to send messages
for (int i = 0; i < 5; i++) {
String message=UUID.randomUUID().toString();
pubClient.pub(channel, message);
Thread.sleep(1000);
}
//Message Receiver Actively Cancels Subscription
subClient.unsubscribe(channel);
Thread.sleep(1000);
pubClient.pub(channel, "Aliyun Message 2: (subscription cancelled at this time, so this message will not be received)");
//The message publisher ends sending a quit message.
//At this point, if there are other message receivers, the unsubscribe operation will be performed when "quit" is received in listener.onMessage().
pubClient.close(channel);
}
}
Operation result
After entering the correct ApsaraDB for Redis instance access address and password, run the above Java program, and the output is as follows.
Publish > Channel: KVStore Channel - A > Message:Aliyun Message 1: (No subscription at this time, so this message will not be received) Subscription message SUBSCRIBE begins - ---------------------------------------------------------------------------------------------------------------- SUBSCRIBE > Channel: KVStore Channel-A Publish > Channel: KVStore Channel - A > Message:0f9c2cee-77c7-4498-89a0-1dc5a2f65889 Subscription (SUBSCRIBE) < Channel: KVStore Channel-A > Message received: 0f9c2cee-77c7-4498-89a0-1dc5a2f65889 Publish > Channel: KVStore Channel - A > Message sent: ed5924a9-016b-469b-8203-7db63d06f812 < Subscription (SUBSCRIBE)< Channel: KVStore Channel-A > Received Message:ed5924a9-016b-469b-8203-7db63d06f812 Publish > Channel: KVStore Channel - A > Message:f1f84e0f-8f35-4362-9567-25716b1531cd < Subscription (SUBSCRIBE)< Channel: KVStore Channel-A > Received Message:f1f84e0f-8f35-4362-9567-25716b1531cd Publish > Channel: KVStore Channel - A > Message:746bde54-af8f-44d7-8a49-37d1a245d21b < Subscription (SUBSCRIBE)< Channel: KVStore Channel-A > Received Message:746bde54-af8f-44d7-8a49-37d1a245d21b Publish > Channel: KVStore Channel - A > Message:8ac3b2b8-9906-4f61-8cad-84fc1f15a3ef < Subscription (SUBSCRIBE)< Channel: KVStore Channel-A > Message received: 8ac3b2b8-9906-4f61-8cad-84fc1f15a3ef "> Unsubscription (UNSUBSCRIBE)> Channel: KVStore Channel-A The subscription message SUBSCRIBE is over - -------------------------------------------------------------------------------------------------------------- Publish > Channel: KVStore Channel - A > Message:Aliyun Message 2: (subscription cancelled at this time, so this message will not be received) Publishing End > Channel: KVStore Channel - A > Message: quit
In the above example, only one publisher and one subscriber are demonstrated. In fact, both publishers and subscribers can be multiple, and the channel for sending messages can be multiple. Just modify the above code slightly.
Pipeline transmission
Code Example 1
Performance comparison
package pipeline.kvstore.aliyun.com;
import java.util.Date;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
public class RedisPipelinePerformanceTest {
static final String host = "xxxxxx.m.cnhza.kvstore.aliyuncs.com";
static final int port = 6379;
static final String password = "password";
public static void main(String[] args) {
Jedis jedis = new Jedis(host, port);
//Instance password for ApsaraDB for Redis
String authString = jedis.auth(password);// password
if (!authString.equals("OK")) {
System.err.println("AUTH Failed: " + authString);
jedis.close();
return;
}
//Continuous execution of multiple command operations
final int COUNT=5000;
String key = "KVStore-Tanghan";
// 1 - - Do not use pipeline operations
jedis.del(key);//Initialize key
Date ts1 = new Date();
for (int i = 0; i < COUNT; i++) {
//Send a request and receive a response (Send Request and Receive Response)
jedis.incr(key);
}
Date ts2 = new Date();
System.out.println("No need Pipeline > value by:"+jedis.get(key)+" > Operation time:" + (ts2.getTime() - ts1.getTime())+ "ms");
//2 - Contrast pipeline Operations
jedis.del(key);//Initialize key
Pipeline p1 = jedis.pipelined();
Date ts3 = new Date();
for (int i = 0; i < COUNT; i++) {
//Send Request
p1.incr(key);
}
//Receive Response
p1.sync();
Date ts4 = new Date();
System.out.println("Use Pipeline > value by:"+jedis.get(key)+" > Operation time:" + (ts4.getTime() - ts3.getTime())+ "ms");
jedis.close();
}
}
Operation Result 1
After entering the correct ApsaraDB for Redis instance access address and password, run the above Java program, and the output is as follows. It can be seen that pipeline is much faster to use.
No Pipeline > value: 5000 > operation time: 5844ms Pipeline > value: 5000 > operation time: 78ms
Code Example 2
When using pipeline in Jedis, there are two ways to process response data. Refer to the following code example.
package pipeline.kvstore.aliyun.com;
import java.util.List;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
public class PipelineClientTest {
static final String host = "xxxxxxxx.m.cnhza.kvstore.aliyuncs.com";
static final int port = 6379;
static final String password = "password";
public static void main(String[] args) {
Jedis jedis = new Jedis(host, port);
// Instance password for ApsaraDB for Redis
String authString = jedis.auth(password);// password
if (!authString.equals("OK")) {
System.err.println("AUTH Failed: " + authString);
jedis.close();
return;
}
String key = "KVStore-Test1";
jedis.del(key);//Initialization
// --------- Method1
Pipeline p1 = jedis.pipelined();
System.out.println("-----Method 1-----");
for (int i = 0; i < 5; i++) {
p1.incr(key);
System.out.println("Pipeline Send request");
}
// Send the request completed and start receiving the response
System.out.println("Send the request completed and start receiving the response");
List<Object> responses = p1.syncAndReturnAll();
if (responses == null || responses.isEmpty()) {
jedis.close();
throw new RuntimeException("Pipeline error: No response was received");
}
for (Object resp : responses) {
System.out.println("Pipeline Receiving response Response: " + resp.toString());
}
System.out.println();
//--------- Method2
System.out.println("-----Method 2-----");
jedis.del(key);//Initialization
Pipeline p2 = jedis.pipelined();
//Response needs to be declared first
Response<Long> r1 = p2.incr(key);
System.out.println("Pipeline Send request");
Response<Long> r2 = p2.incr(key);
System.out.println("Pipeline Send request");
Response<Long> r3 = p2.incr(key);
System.out.println("Pipeline Send request");
Response<Long> r4 = p2.incr(key);
System.out.println("Pipeline Send request");
Response<Long> r5 = p2.incr(key);
System.out.println("Pipeline Send request");
try{
r1.get(); //The response has not been received yet, so this operation will go wrong.
}catch(Exception e){
System.out.println(" <<< Pipeline error: No response has been received yet. >>> ");
}
// Send the request completed and start receiving the response
System.out.println("Send the request completed and start receiving the response");
p2.sync();
System.out.println("Pipeline Receiving response Response: " + r1.get());
System.out.println("Pipeline Receiving response Response: " + r2.get());
System.out.println("Pipeline Receiving response Response: " + r3.get());
System.out.println("Pipeline Receiving response Response: " + r4.get());
System.out.println("Pipeline Receiving response Response: " + r5.get());
jedis.close();
}
}
Operation result 2
Method 1 Pipeline sends requests Pipeline sends requests Pipeline sends requests Pipeline sends requests Pipeline sends requests Send the request completed and start receiving the response Pipeline Receives Response: 1 Pipeline Receives Response: 2 Pipeline Receives Response: 3 Pipeline Receives Response: 4 Pipeline Receives Response: 5 Method 2 Pipeline sends requests Pipeline sends requests Pipeline sends requests Pipeline sends requests Pipeline sends requests << Pipeline error: response has not yet been received > Send the request completed and start receiving the response Pipeline Receives Response: 1 Pipeline Receives Response: 2 Pipeline Receives Response: 3 Pipeline Receives Response: 4 Pipeline Receives Response: 5
transaction processing
Code Example 1: Two client s operate on different key s
package transcation.kvstore.aliyun.com;
import java.util.List;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
public class KVStoreTranscationTest {
static final String host = "xxxxxx.m.cnhza.kvstore.aliyuncs.com";
static final int port = 6379;
static final String password = "password";
//** Note that the contents of these two key s are different
static String client1_key = "KVStore-Transcation-1";
static String client2_key = "KVStore-Transcation-2";
public static void main(String[] args) {
Jedis jedis = new Jedis(host, port);
// Instance password for ApsaraDB for Redis
String authString = jedis.auth(password);//password
if (!authString.equals("OK")) {
System.err.println("Authentication failed: " + authString);
jedis.close();
return;
}
jedis.set(client1_key, "0");
//Start another thread to simulate another client
new KVStoreTranscationTest().new OtherKVStoreClient().start();
Thread.sleep(500);
Transaction tx = jedis.multi();//Start business
//The following actions are submitted centrally to the server side for processing as "atomic operations"
tx.incr(client1_key);
tx.incr(client1_key);
Thread.sleep(400);//The suspension of Thread here has no effect on consecutive operations in transactions, nor can other Thread operations be performed.
tx.incr(client1_key);
Thread.sleep(300);//The suspension of Thread here has no effect on consecutive operations in transactions, nor can other Thread operations be performed.
tx.incr(client1_key);
Thread.sleep(200);//The suspension of Thread here has no effect on consecutive operations in transactions, nor can other Thread operations be performed.
tx.incr(client1_key);
List<Object> result = tx.exec();//Submission execution
//Parse and print out the results
for(Object rt : result){
System.out.println("Client 1 > Transaction> "+rt.toString());
}
jedis.close();
}
class OtherKVStoreClient extends Thread{
@Override
public void run() {
Jedis jedis = new Jedis(host, port);
// Instance password for ApsaraDB for Redis
String authString = jedis.auth(password);// password
if (!authString.equals("OK")) {
System.err.println("AUTH Failed: " + authString);
jedis.close();
return;
}
jedis.set(client2_key, "100");
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Client 2 > "+jedis.incr(client2_key));
}
jedis.close();
}
}
}
Operation Result 1
Client 2 > 101 Client 2 > 102 Client 2 > 103 Client 2 > 104 Client 1 > Transaction> 1 Client 1 > Transaction> 2 Client 1 > Transaction> 3 Client 1 > Transaction> 4 Client 1 > Transaction> 5 Client 2 > 105 Client 2 > 106 Client 2 > 107 Client 2 > 108 Client 2 > 109 Client 2 > 110
Code Example 2: Two client s operate on the same key
Modify the above code slightly so that two client s operate on the same key and the rest remains unchanged.
... ...
//** Note that the contents of these two key s are now the same
static String client1_key = "KVStore-Transcation-1";
static String client2_key = "KVStore-Transcation-1";
... ...
Operation result 2
Client 2 > 101 Client 2 > 102 Client 2 > 103 Client 2 > 104 Client 1 > Transaction> 105 Client 1 > Transaction> 106 Client 1 > Transaction> 107 Client 1 > Transaction> 108 Client 1 > Transaction> 109 Client 2 > 110 Client 2 > 111 Client 2 > 112 Client 2 > 113 Client 2 > 114 Client 2 > 115