Installation and use of redis

Keywords: Redis Jedis Java Ruby

Redis
Redis Command Reference Web Site: http://doc.redisfans.com/

  1. Introduction to Redis
    Redis is completely open source, free of charge, complies with BSD protocol, and is a high-performance key-value database.
    Redis and other key - value caching products have three features:
  1. Redis supports data persistence, can save data in memory in disk, and can be loaded again when restarted for use.
  2. Redis not only supports simple key-value data, but also provides storage of list, set, zset, hash and other data structures.
  3. Redis supports backup of data, i.e. master-slave mode.
    2.Redis Installation
    1) Installation under Window s
    64-bit download address: https://github.com/MSOpenTech/redis/releases.
    32-bit download address: http://vdisk.weibo.com/s/dbUhxKrgqodB
    (If 32 bits are used, use stand-alone mode)
    Redis supports 32 and 64 bits. This needs to be selected according to the actual situation of your system platform. Here we download the Redis-x64-xxx.zip compressed package to disk C. After decompression, rename the folder redis.

Pictures. png

Download and decompress the following files in the decompressed directory

Pictures. png

Open a cmd window and use the cd command to switch directories to C:redis to run redis-server.exe redis.windows.conf.
If you want convenience, you can add redis path to the system's environment variables, so that you don't need to re-enter the path, the latter redis.windows.conf can be omitted, if omitted, the default will be enabled. After input, the following interface will be displayed:

Pictures. png

At this time, another cmd window will be opened. Do not close the original window, or you will not be able to access the server.
Switch to redis directory and run redis-cli.exe-h<ip>-p<port(default 6379)>
For example: redis-cli.exe-h 127.0.0.1-p 6379.
Set the key value pair set myKey abc
Take out the key pair get myKey

Pictures. png

2) Installation under Linux
Download address: http://redis.io/download Download the latest version of the document.

$ wget http://download.redis.io/releases/redis-2.8.17.tar.gz
$ tar xzf redis-2.8.17.tar.gz
$ cd redis-2.8.17
$ make

After making, the compiled redis service program redis-server will appear in the redis-2.8.17 directory, and the client program redis-cli for testing. The two programs are located in the installation directory src directory:
Start the redis service below.

$ cd src
$ ./redis-server

Note that this way redis is started using the default configuration. You can also tell redis to start with the following command using the specified configuration file by using the startup parameters.

$ cd src
$ ./redis-server redis.conf

redis.conf is a default configuration file. We can use our own configuration files as needed.
After starting the redis service process, you can use the test client program redis-cli to interact with the redis service. For example:

$ cd src
$ ./redis-cli
redis> set foo bar
OK
redis> get foo
"bar"

3) Building redis cluster under Windows
ruby environment preparation
Download 64-bit Ruby Installer and install address http://rubyinstaller.org/downloads/
Check the following three environment variables that do not need to be configured

Pictures. png

Install RubyGems
Downloaded is a compressed package that unzips setup.rb and installs rubyGems
Because of the wall, ruby's own source is sometimes very slow. We'll replace it with Taobao's source, otherwise installing redis dependency below will fail. (-)/
Running under cmd
gem sources --remove https://rubygems.org/ Delete the original source
gem sources -a http://ruby.taobao.org Add Taobao Source (if the addition fails, try it) https://ruby.taobao.org or http://gems.ruby-china.org)
Gem sources-l View existing sources
gem install redis install redis dependencies
Use redis cluster
Just follow the instructions in the document. Here are the details. http://doc.redisfans.com/topic/cluster-tutorial.html#id5
To make the cluster work properly, we need at least three master nodes. So we create six nodes, three master nodes and three slave nodes. Please look at the document in detail. Let me simplify the steps of the document.
1. Create 6 folders 7000-7005, respectively
Here is the redis installed by each machine in the cluster. Put a downloaded redis in each folder, for example

Pictures. png

2. Create the configuration file redis.conf
Several other 7000-7004 folders and so on, pay attention to modifying the corresponding port number
Bind < IP > case: 192.168.1.202
port 7005
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
appendonly yes
In the document
The cluster-enabled option is used to open the cluster mode of an instance.
The cluster-conf-file option sets the path to save the node configuration file, with the default value of nodes.conf.
The nodes.conf node configuration file is created by the Redis cluster at startup and updated automatically when necessary without human modification.
3. Create startup script 7005.bat
This way, you don't always have to knock on commands and change your name at will. The same goes for several other folders.
@echo off
redis-server.exe redis.conf
@pause
4. Creating Clusters
1. Configure each instance according to the above, mainly change the port number, run 7000.bat-7005.bat script to start six redis instances.
2.cd to run commands in redis-trib.rb directory
Redis-trib.rb create-replicas 1 < IP >: < port > < IP >: < port > < IP > < IP >: < port > < IP >: < port > < port > < IP > < port > < IP > < IP > < port > < IP
Example: redis-trib.rb create--replicas 1 127.0.0.1:7000 127.0.0.0.1:7001 127.0.0.1:7002 127.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005

Pictures. png

Print out the configuration information, now the master is 7000 7001 7002 of these three machines, redis will do CRC16 check on the key and store them separately. No problem, just type yes.
5. Viewing Configured Cluster Information
To view the configuration information of the cluster, execute the following commands:
redis-cli.exe -c -h 127.0.0.1 -p 7003 cluster nodes
Connect any Redis cluster node and you will see that the following information is successful:

E:\redis-3.0.501>redis-cli.exe -c -h 127.0.0.1 -p 7002 cluster nodes
aa618ef5e865851d33b71d18eb709766fc18a277 127.0.0.1:7005 slave f673e19b77818c431e61dfb6eb5f3ba321e661c8 0 1468662482348 5 connected
9d9e45376bfc47f816734dadd7f0668f5c713470 127.0.0.1:7003 master - 0 14686624793233 connected 10923-16383
f673e19b77818c431e61dfb6eb5f3ba321e661c8 127.0.0.1:7002 myself,master - 0 0 2 connected 5461-10922
60c544fe2f6e6ea11dfeacd3c778c586bc977b1f 127.0.0.1:7001 master - 0 14686624813441 connected 0-5460
e27dae6b7bac30c7795d3f198ba2324c0c1fa65b 127.0.0.1:7006 slave 9d9e45376bfc47f816734dadd7f0668f5c713470 0 1468662477240 6 connected
773c908e6312b21d938e1185e1cb30dd8b9d9823 127.0.0.1:7004 slave 60c544fe2f6e6ea11dfeacd3c778c586bc977b1f 0 1468662476511 4 connected

6. Dynamically adding a node to the cluster
redis-trib.rb add-node 127.0.0.1:7008 (node to be added) 127.0.0.1:7002 (any running node)

3. Spring MVC integration redis
Dependent on jar packages:

Pictures. png


Pictures. png

 

spring-redis.xml

<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">

<property name="maxTotal" value="${redis.maxTotal}" />

<property name="maxIdle" value="${redis.maxIdle}" />

<property name="numTestsPerEvictionRun"value="${redis.numTestsPerEvictionRun}"/>

<property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}" />

<property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}" />

<property name="softMinEvictableIdleTimeMillis" value="${redis.softMinEvictableIdleTimeMillis}" />

<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />

<property name="testOnBorrow" value="true" />

<property name="testWhileIdle" value="true" />

<property name="blockWhenExhausted" value="false" />
</bean>

<bean id="redisClient" class="redis.clients.jedis.JedisPool">
<constructor-arg name="host" value="${redis.host}"></constructor-arg>
<constructor-arg name="port" value="${redis.port}"></constructor-arg>
<constructor-arg name="poolConfig" ref="jedisPoolConfig"></constructor-arg>
</bean>

Pictures. png

RedisModel entity class
package com.sinog2c.model.redis;

import java.io.Serializable;

public class RedisModel implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = -6762060250356126904L;
public static final String OBJECT_KEY = "USER";

private String key;
private Object obj;
private Integer seconds;//Expiration time (in milliseconds)

public RedisModel(){}

public RedisModel(String key, Object obj){
    this.key = key;
    this.obj = obj;
}

public RedisModel(String key, Object obj, Integer seconds){
    this.key = key;
    this.obj = obj;
    this.seconds = seconds;
}

public String getKey() {
    return key;
}
public void setKey(String key) {
    this.key = key;
}
public Object getObj() {
    return obj;
}
public void setObj(Object obj) {
    this.obj = obj;
}
public Integer getSeconds() {
    return seconds;
}
public void setSeconds(Integer seconds) {
    this.seconds = seconds;
}

public String getObjectKey() {
return OBJECT_KEY;
}
}

Service layer
JedisClientService.java
package com.sinog2c.service.api.redis;

import com.sinog2c.model.redis.RedisModel;

public interface JedisClientService {
/**
* Add data (Key-Value) to redis cache
* @param redis
* @return
/
String set(RedisModel redis);
/*
* Add data (hash) to redis cache
* @param redis
* @return
/
long hset(RedisModel redis);
/*
* Getting data from redis cache (Key-Value)
* @param key
* @return
/
Object get(String key);
/*
* Getting data from redis cache (hash)
* @param redis
* @return
/
public Object hget(RedisModel redis);
/*
* Delete data from redis cache
* @param key
* @return
/
long del(String key);
/*
* Delete data (hash) from redis cache
* @param key
* @return
/
long hdel(RedisModel redis);
/*
* Setting the expiration time of key
* @param key
* @param second
* @return
/
long expire(String key, int second);
/*
* Verify that a key exists
* @param key
* @return
/
Boolean exists(String key);
/*
* Confirm the existence of key in map
* @param key
* @return
/
Boolean hexists(RedisModel redis);
/*
* Delete current DB data
* @return
/
String flushDB();
/*
* Clean up all data
* @return
/
String flushAll();
/*
* string increment operation with the name key (obj value in RedisModel is long type)
* @param redis
* @return
/
long incrBy(RedisModel redis);
/*
* string reduction operation with the name key (obj value in RedisModel is long type)
* @param redis
* @return
/
long decrBy(RedisModel redis);
/*
* Add an element with value at the end of the list named key
* @param redis
* @return
/
long rpush(RedisModel redis);
/*
* Add an element with value to the list header named key
* @param redis
* @return
/
long lpush(RedisModel redis);
/*
* Find the length of the list with the name key
* @param key
* @return
/
long llen(String key);
/*
* Find the elements between start and end in a list named key
* @param key
* @param start
* @param end
* @return
/
Object lrange(String key, long start, long end);
/*
* intercept a list with the name key
* @param key
* @param start
* @param end
* @return
*/
Object ltrim(String key, long start, long end);

}

Single-machine version implementation class (if cluster version is used instead of this implementation class)
package com.sinog2c.service.impl.redis;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import com.sinog2c.model.redis.RedisModel;
import com.sinog2c.service.api.redis.JedisClientService;
import com.sinog2c.util.common.redis.ObjectsTranscoder;

@Service("jedisClientSingleService")
public class JedisClientSingleServiceImpl implements JedisClientService {

@Autowired  
private JedisPool jedisPool;   
/**
 * Add data to redis cache
 */
@Override
public String set(RedisModel redis) {
    Jedis jedis = jedisPool.getResource();
    String string = "faile"; 
    try {
        if (redis != null) {
            String key = redis.getKey();
            Integer seconds = redis.getSeconds();
            string = jedis.set(key.getBytes(), ObjectsTranscoder.getInstance().serialize(redis.getObj()));
            if (seconds != null) {
                jedis.expire(key.getBytes(), seconds);
            }
        }
    } catch (Exception e) {

    } finally {
        jedis.close();
    }
    return string;
}
/**
 * Add data (Hash) to redis cache
 */

@Override
public long hset(RedisModel redis){
    Jedis jedis = jedisPool.getResource();
    long flag = 0; 
    try {
        if (redis != null) {
            String key = redis.getKey();
            Integer seconds = redis.getSeconds();
            flag = jedis.hset(redis.getObjectKey().getBytes(),key.getBytes(), ObjectsTranscoder.getInstance().serialize(redis.getObj()));
            if (seconds != null) {
                jedis.expire(key.getBytes(), seconds);
            }
        }
    } catch (Exception e) {

    } finally {
        jedis.close();
    }
    return flag;
}

/**
 * Getting data from redis cache
 */
@Override
public Object get(String key) {
    Jedis jedis = jedisPool.getResource(); 
    try {
        if(key != null && !"".equals(key)){
            byte[] bytes = jedis.get(key.getBytes());
            return ObjectsTranscoder.getInstance().deserialize(bytes);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        jedis.close();
    }
    return null;
} 
/**
 * Getting data from redis cache (hash)
 */
@Override
public Object hget(RedisModel redis) {
    Jedis jedis = jedisPool.getResource(); 
    try {
        String key = redis.getKey();
        if(key != null && !"".equals(key)){
            byte[] bytes = jedis.hget(redis.getObjectKey().getBytes(),key.getBytes());
            return ObjectsTranscoder.getInstance().deserialize(bytes);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        jedis.close();
    }
    return null;
}
/**
 * Delete data from redis cache
 */
@Override  
public long del(String key) {
    if(key != null && !"".equals(key)){
        Jedis jedis = jedisPool.getResource();  
        Long result = jedis.del(key.getBytes());  
        jedis.close();  
        return result;  
    }
    return 0;
}
/**
 * Delete data from redis cache
 */
@Override  
public long hdel(RedisModel redis) {
    if(redis != null){
        String key = redis.getKey(); 
        if(key != null && !"".equals(key)){
            Jedis jedis = jedisPool.getResource();  
            Long result = jedis.hdel(key.getBytes());  
            jedis.close();  
            return result; 
        } 
    }
    return 0;
}

/**
 * Setting the expiration time of key
 */
@Override  
public long expire(String key, int second) {
    if(key != null && !"".equals(key)){
        Jedis jedis = jedisPool.getResource();  
        Long result = jedis.expire(key.getBytes(), second);  
        jedis.close();  
        return result;  
    }
    return 0;
}
/**
 * string increment operation with the name key (obj value in RedisModel is long type)
 */
@Override  
public long incrBy(RedisModel redis) {  
    if(redis != null){
        Jedis jedis = jedisPool.getResource(); 
        long result = jedis.incrBy(redis.getKey().getBytes(), Long.parseLong(redis.getObj()+""));
        jedis.close();  
        return result; 
    }  
    return 0;  
}
/**
 * string reduction operation with the name key (obj value in RedisModel is long type)
 */
@Override
public long decrBy(RedisModel redis) {
    if(redis != null){
        Jedis jedis = jedisPool.getResource();
        long result = jedis.decrBy(redis.getKey().getBytes(), Long.parseLong(redis.getObj()+""));
        jedis.close();
        return result;
    }
    return 0;
}
/**
 * Add an element with value at the end of the list named key
 */
@Override
public long rpush(RedisModel redis) {
    if(redis != null){
        Jedis jedis = jedisPool.getResource(); 
        long result = jedis.rpush(redis.getKey().getBytes(), ObjectsTranscoder.getInstance().serialize(redis.getObj()));
        jedis.close();
        return result;
    }
    return 0;
}
/**
 * Add an element with value to the list header named key
 */
@Override
public long lpush(RedisModel redis) {
    if(redis != null){
        Jedis jedis = jedisPool.getResource();
        long result = jedis.lpush(redis.getKey().getBytes(), ObjectsTranscoder.getInstance().serialize(redis.getObj()));
        jedis.close();
        return result;
    }
    return 0;
}
/**
 * Find the length of the list with the name key
 */
@Override
public long llen(String key) {
    if(key != null && !"".equals(key)){
        Jedis jedis = jedisPool.getResource(); 
        long result =  jedis.llen(key.getBytes());
        jedis.close();
        return result;
    }
    return 0;
}
/**
 * Find the elements between start and end in a list named key
 */
@Override
public Object lrange(String key, long start, long end) {
    if(key != null && !"".equals(key)){
        Jedis jedis = jedisPool.getResource(); 
        List<byte[]> list = jedis.lrange(key.getBytes(), start, end);
        jedis.close();
        return listByteArrayToObject(list);
    } 
    return null;

}
/**
 * Intercept a list with the name key
 */
@Override
public Object ltrim(String key, long start, long end) {
    if(key != null && !"".equals(key)){
        Jedis jedis = jedisPool.getResource(); 
        String result = jedis.ltrim(key.getBytes(), start, end);
        jedis.close();
        return result;
    }
    return null;
}
/**
 * Verify that a key exists
 * @param key
 * @return
 */
@Override
public Boolean exists(String key) {
    Jedis jedis = jedisPool.getResource();
    Boolean flag = jedis.exists(key);
    jedis.close();
    return flag;
}
/**
 * Confirm the existence of key in map
 * @param key
 * @return
 */
@Override
public Boolean hexists(RedisModel redis) {
    Boolean flag = false;
    if(redis != null){
        String key = redis.getKey();
        if(key != null && !"".equals(key)){
            Jedis jedis = jedisPool.getResource();
            flag = jedis.hexists(redis.getObjectKey().getBytes(), key.getBytes());
            jedis.close();
        }
    }

    return flag;
}
/**
 * Delete current DB data
 * @return
 */
@Override 
public String flushDB(){
    Jedis jedis = jedisPool.getResource();  
    String result = jedis.flushDB();  
    jedis.close();  
    return result; 
}
/**
 * Clean up all data
 * @return
 */
@Override 
public String flushAll(){
    Jedis jedis = jedisPool.getResource();  
    String result = jedis.flushAll();  
    jedis.close();  
    return result;
}
/**
 * Convert List < byte []> to List < Object >
 * @param list
 * @return
 */
private Object listByteArrayToObject(List<byte[]> list){
    List<Object> result = new ArrayList<Object>();
    if(list != null && list.size() > 0){
        for(int i=0; i<list.size(); i++){
            result.add(ObjectsTranscoder.getInstance().deserialize(list.get(i)));
        }
        return result;
    } else {
        return "";
    }
}

}
Cluster implementation classes (standalone version does not need to implement classes at this time)

package com.sinog2c.service.impl.redis;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;

import com.sinog2c.model.redis.RedisModel;
import com.sinog2c.service.api.redis.JedisClientService;
import com.sinog2c.util.common.redis.ObjectsTranscoder;
/**

  • Class Description: Cluster Version Implementation
  • @ author Xu Jie
  •  

*/
@Service("jedisClientClusterServcie")
public class JedisClientClusterServcieImpl implements JedisClientService {
@Autowired
private JedisCluster jedisCluster;

/**
 * Add data (Key-Value) to redis cache
 */
@Override
public String set(RedisModel redis) {
    String string = "faile"; 
    try {
        if (redis != null) {
            String key = redis.getKey();
            Integer seconds = redis.getSeconds();
            string = jedisCluster.set(key.getBytes(), ObjectsTranscoder.getInstance().serialize(redis.getObj()));
            if (seconds != null) {
                jedisCluster.expire(key.getBytes(), seconds);
            }
        }
    } catch (Exception e) {
        
    } 
    return string;
}

/**
 * Add data (Hash) to redis cache
 */
@Override
public long hset(RedisModel redis) {
    long log = 0; 
    try {
        if (redis != null) {
            String key = redis.getKey();
            Integer seconds = redis.getSeconds();
            log = jedisCluster.hset(redis.getObjectKey().getBytes(),key.getBytes(), ObjectsTranscoder.getInstance().serialize(redis.getObj()));
            if (seconds != null) {
                jedisCluster.expire(key.getBytes(), seconds);
            }
        }
    } catch (Exception e) {
        
    } 
    return log;
}
/**
 * Getting data from redis cache (Key-Value)
 */
@Override
public Object get(String key) {
    try {
        if(key != null && !"".equals(key)){
            byte[] bytes = jedisCluster.get(key.getBytes());
            return ObjectsTranscoder.getInstance().deserialize(bytes);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } 
    return null;
} 

/**
 * Getting data from redis cache (hash)
 */
@Override
public Object hget(RedisModel redis) {
    try {
        if(redis != null){
            String key = redis.getKey();
            if(key != null && !"".equals(key)){
                byte[] bytes = jedisCluster.hget(redis.getObjectKey().getBytes(),key.getBytes());
                return ObjectsTranscoder.getInstance().deserialize(bytes);
            }
        }
        
    } catch (Exception e) {
        e.printStackTrace();
    } 
    return null;
} 
/**
 * Delete data from redis cache
 */
@Override  
public long del(String key) {
    if(key != null && !"".equals(key)){
        Long result = jedisCluster.del(key.getBytes());  
        return result;  
    }
    return 0;
}
/**
 * Delete data (hash) from redis cache
 * @param key
 * @return
 */
@Override
public long hdel(RedisModel redis) {
    if(redis != null){
        String key = redis.getKey();
        if(key != null && !"".equals(key)){
            Long result = jedisCluster.hdel(redis.getObjectKey().getBytes(), key.getBytes());  
            return result;  
        }
    }
    return 0;
}
/**
 * Setting the expiration time of key
 */
@Override  
public long expire(String key, int second) {
    if(key != null && !"".equals(key)){
        Long result = jedisCluster.expire(key.getBytes(), second);  
        return result;  
    }
    return 0;
}
/**
 * Verify that a key exists
 * @param key
 * @return
 */
@Override
public Boolean exists(String key) {
    Boolean flag = jedisCluster.exists(key);
    return flag;
}
/**
 * Confirm the existence of key in map
 * @param key
 * @return
 */
@Override
public Boolean hexists(RedisModel redis) {
    Boolean flag = false;
    if(redis != null){
        String key = redis.getKey();
        if(key != null && !"".equals(key)){
            flag = jedisCluster.hexists(redis.getObjectKey().getBytes(), key.getBytes());
        }
    }
    return flag;
}
/**
 * Delete current DB data
 * @return
 */
@SuppressWarnings("deprecation")
@Override 
public String flushDB(){
    String result = jedisCluster.flushDB();  
    return result; 
}
/**
 * Clean up all data
 * @return
 */
@SuppressWarnings("deprecation")
@Override 
public String flushAll(){
    String result = jedisCluster.flushAll();  
    return result;
}
/**
 * string increment operation with the name key (obj value in RedisModel is long type)
 */
@Override  
public long incrBy(RedisModel redis) {  
    if(redis != null){
        long result = jedisCluster.incrBy(redis.getKey().getBytes(), Long.parseLong(redis.getObj()+""));
        return result; 
    }  
    return 0;  
}
/**
 * string reduction operation with the name key (obj value in RedisModel is long type)
 */
@Override
public long decrBy(RedisModel redis) {
    if(redis != null){
        long result = jedisCluster.decrBy(redis.getKey().getBytes(), Long.parseLong(redis.getObj()+""));
        return result;
    }
    return 0;
}
/**
 * Add an element with value at the end of the list named key
 */
@Override
public long rpush(RedisModel redis) {
    if(redis != null){
        long result = jedisCluster.rpush(redis.getKey().getBytes(), ObjectsTranscoder.getInstance().serialize(redis.getObj()));
        return result;
    }
    return 0;
}
/**
 * Add an element with value to the list header named key
 */
@Override
public long lpush(RedisModel redis) {
    if(redis != null){
        long result = jedisCluster.lpush(redis.getKey().getBytes(), ObjectsTranscoder.getInstance().serialize(redis.getObj()));
        return result;
    }
    return 0;
}
/**
 * Find the length of the list with the name key
 */
@Override
public long llen(String key) {
    if(key != null && !"".equals(key)){
        long result =  jedisCluster.llen(key.getBytes());
        return result;
    }
    return 0;
}
/**
 * Find the elements between start and end in a list named key
 */
@Override
public Object lrange(String key, long start, long end) {
    if(key != null && !"".equals(key)){
        List<byte[]> list = jedisCluster.lrange(key.getBytes(), start, end);
        return listByteArrayToObject(list);
    } 
    return null;
    
}
/**
 * Intercept a list with the name key
 */
@Override
public Object ltrim(String key, long start, long end) {
    if(key != null && !"".equals(key)){
        String result = jedisCluster.ltrim(key.getBytes(), start, end);
        return result;
    }
    return null;
}
/**
 * Convert List < byte []> to List < Object >
 * @param list
 * @return
 */
private Object listByteArrayToObject(List<byte[]> list){
    List<Object> result = new ArrayList<Object>();
    if(list != null && list.size() > 0){
        for(int i=0; i<list.size(); i++){
            result.add(ObjectsTranscoder.getInstance().deserialize(list.get(i)));
        }
        return result;
    } else {
        return "";
    }
}

}

ObjectsTranscoder class (serializes and deserializes objects)

package com.sinog2c.util.common.redis;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**

  • Serialization and deserialization of objects

  • @ author Xu Jie

  •  
  • @ Param < M > object
    */
    public class ObjectsTranscoder<M extends Serializable> extends SerializeTranscoder {

    private ObjectsTranscoder(){}
    private static ObjectsTranscoder single=null;
    // Static Factory Method
    public static ObjectsTranscoder getInstance() {
    if (single == null) {
    single = new ObjectsTranscoder();
    }
    return single;
    }

    public byte[] serialize(Object value) {
    if (value == null) {
    throw new NullPointerException("Can't serialize null");
    }
    byte[] result = null;
    ByteArrayOutputStream bos = null;
    ObjectOutputStream os = null;
    try {
    bos = new ByteArrayOutputStream();
    os = new ObjectOutputStream(bos);
    M m = (M) value;
    os.writeObject(m);
    os.close();
    bos.close();
    result = bos.toByteArray();
    } catch (IOException e) {
    throw new IllegalArgumentException("Non-serializable object", e);
    } finally {
    close(os);
    close(bos);
    }
    return result;
    }

    public M deserialize(byte[] in) {
    M result = null;
    ByteArrayInputStream bis = null;
    ObjectInputStream is = null;
    try {
    if (in != null) {
    bis = new ByteArrayInputStream(in);
    is = new ObjectInputStream(bis);
    result = (M) is.readObject();
    is.close();
    bis.close();
    }
    } catch (IOException e) {

     } catch (ClassNotFoundException e) {  
    
     } finally {  
         close(is);  
         close(bis);  
     }  
     return result;  
    

    }
    }

SerializeTranscoder class

package com.sinog2c.util.common.redis;

import java.io.Closeable;

import org.apache.log4j.Logger;

public abstract class SerializeTranscoder {

protected static Logger logger = Logger.getLogger(SerializeTranscoder.class);

public abstract byte[] serialize(Object value);

public abstract Object deserialize(byte[] in);

public void close(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (Exception e) {
             logger.info("Unable to close " + closeable, e); 
        }
    }
}

The above is my share. Thank you for your patience. Finally, I share a group of my own back-end technology. I collect a lot of Java architecture information in the group. You can get free information from the group. Group number: 680075317. You can also join the group to communicate with each other. For example, when you encounter technical bottlenecks, you can't get an interview. Some exchange learning!

Posted by jbulaswad on Thu, 01 Aug 2019 23:20:36 -0700