Simple redis cache operations (get, put)

Keywords: Java Redis Jedis Database Spring

Simple redis cache operations (get, put)

This article describes simple redis caching operations, including introducing the jedisjar package, configuring redis, some tools needed by RedisDao, put ting data into redis, fetching data from redis, and logic for accessing redis.

1. Introducing the jedis jar package

<!-- java Visit redis Of jar package jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.7.3</version>
</dependency>
<!-- protostuff Serialization Dependency -->
<dependency>
    <groupId>com.dyuproject.protostuff</groupId>
    <artifactId>protostuff-core</artifactId>
    <version>1.0.8</version>
</dependency>
<dependency>
    <groupId>com.dyuproject.protostuff</groupId>
    <artifactId>protostuff-runtime</artifactId>
    <version>1.0.8</version>
</dependency>

Note: Why do you want to introduce serialization dependent jar package protostuff?

1) The data extracted from redis is serialized, we need to use protostuff's deserialization operation to talk about converting serialized objects into objects we need

2) When placing data in redis, we need to use protostuff's serialization to convert objects into serialized objects before we can place redis

2. Inject redis into the spring configuration file and put into the ioc container of spring

<!-- injection redis dao -->
<bean id="redisDao" class="org.demo.dao.cache.RedisDao">
  <constructor-arg index="0" value="localhost"></constructor-arg>
  <constructor-arg index="1" value="6379"></constructor-arg>
</bean>

Be careful:

1) The RedisDao path here is my package path, note that you should use your own path when configuring

2) Use the local redis service localhost here

3) The default port for redis service is 6379

3. Some tools needed by RedisDao

  //redis Connection Pool
    private final JedisPool jedisPool;//Generate an empty object from the byte code file of the object
    private RuntimeSchema<Object> schema = RuntimeSchema.createFrom(Object.class);  //Object.class: Get the byte code of the object
    
    public RedisDao(String ip, int port){
        jedisPool = new JedisPool(ip, port);
    }

Be careful:

1) RedisDao requires a redis connection pool, JedisPool, just like a JDBC database connection pool.We initialize this connection pool in the RedisDao constructor

2) We need a tool, RuntimeSchema, that can generate empty objects from the byte code files of the objects.What object do you want to use, you write your object (Object.class: Get the byte code file of the object) at the location of the Object

3) Initialization of connection pool JedisPool requires two parameters: ip, port

4. put data in redis

    //Caching objects to redis
    public String putObject(Object obj){
        //Cache logic:Object --> serialize --> byte[] --> Cache to redis
        try {
            Jedis jedis = jedisPool.getResource();  //Obtain redis Connecting object, equivalent to JDBC Of connection
            try{
                String key = "Object:"+obj.getId();
                //Serialize
                byte[] bytes = ProtostuffIOUtil.toByteArray(seckill, schema, 
                        LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE)); //Buffer objects if they are too large
                //Start Caching
                int timeout = 60*60; //Set a timeout of one hour,Maintain consistency through timeouts
                String result = jedis.setex(key.getBytes(), timeout, bytes);
                return result;
            }finally{
                jedis.close();
            }
        } catch (Exception e) {
            e.printStack();
        }
        return null;
    }

Be careful:

1) Cache logic: Object --> Serialization operations --> byte [] --> Write redis.That is to serialize the object before writing redis!

2) We must get the connection object of redis from the connection pool before operating redis

5. get data from redis

    //from redis Queries in Cache
    public Object getObject(long id){
        //redis Operational logic
        try {
            Jedis jedis = jedisPool.getResource();   //Cache connection object, equivalent to database connection object connection
            try {
                String key = "Object:"+id;
                //Entity object does not implement internal serialization
                //Cache logic:getByte[] --> Deserialize --> Object
                byte[] bytes = jedis.get(key.getBytes()); //from jedis Gets the serialized object array of the target object in
                if(bytes != null){
                    //Deserialization logic
                    Object obj = schema.newMessage();  //adopt schema Generate a new empty object
                    ProtostuffIOUtil.mergeFrom(bytes, obj, schema);  //Deserialize
                    return obj;
                }
                
            } finally {
                jedis.close();
            }
             
        } catch (Exception e) {
        e.printStack(); }
return null; }

Be careful:

1) Data fetching logic: redis --> get byte [] --> deserialize --> Object

2) When we place data, it is in the form of key-value pairs: id --> obj.When we take data, we take it by id

6. Logic when querying redis

Pseudocode:

get form redis_cache              //Query first redis
if null                           //Without
    get from db                   //Then from the database db query
    if null                       //If it still doesn't
        return null               //Then return to null
    else                          //otherwise
        put into redis_cache      //Now put the data in redis
        return obj                //Play back the data
else                              //If from redis Queried in
    return obj                    //Then return the data directly

Posted by im8kers on Thu, 23 May 2019 10:33:25 -0700