Redis operations with Spring-data

Use Spring-data for Redis operationshttp: //zhaozhiming.github.io/blog/2015/04/12/spring-data-redis/
Redis integrates Spring to use cache instances http://blog.csdn.net/evankaka/ article/details/50396325
Conquering Redis + Jedis + Spring (1) - Configuration & General Operations (GET SET DEL) http://snowolf.iteye.com/blog/1666908

Redis I believe everyone has heard of it, it is an open source The key-value cache database, there are many Java client support, the more famous are Jedis, JRedis, etc. (see here). Of course, we can use the client's native code to implement redis operations, but in fact, the use of these clients has been integrated in spring. Let's take Jedis as an example to introduce the configuration of Redis in Spring.
Download related dependency packages
First of all, you need to download the dependency packages related to spring and redis. The latest jedis version is 2.6.2, and you also need to download the jackson package. This will be explained later. The gradle script example is as follows.
build.gradle
    compile("redis.clients:jedis:" + jedisVersion)
    compile "org.springframework.data:spring-data-redis:" + springDataRedisVersion

    //json
    compile "com.fasterxml.jackson.core:jackson-databind:" + jacksonDatabindVersion
    compile "org.codehaus.jackson:jackson-mapper-asl:" + jacksonVersion
    compile "org.codehaus.jackson:jackson-core-asl:" + jacksonVersion

The spring configuration jedis
is configured as follows in the spring xml configuration file.
  <!-- Configure the redis pool, followed by the maximum number of instances, the maximum number of idle instances, the maximum waiting time (when creating an instance), and whether to verify (when creating an instance) -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.maxTotal}"/>
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
    </bean>

    <!-- redis connection configuration, followed by host ip, port, whether to use pool, (when usePool=true) redis pool configuration -->
    <bean id="jedisFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.host}"/>
        <property name="port" value="${redis.port}"/>
        <property name="usePool" value="true"/>
        <property name="poolConfig" ref="jedisPoolConfig"/>
    </bean>

  <!-- redis template configuration-->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisFactory"/>
        <property name="defaultSerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
    </bean>

Serialization Redis storage is performed
in spring. If the key and value are not serialized, garbled characters will appear in redis. Pay attention to the redis template configuration above. One configuration item is defaultSerializer, which means that when the key and value in redis need to be serialized, the StringRedisSerializer class is used for serialization by default. If serialization is not specified, the content will be garbled.
The serialization classes of spring-data-redis are as follows:
GenericToStringSerializer: Can generalize any object to string and serialize
Jackson2JsonRedisSerializer: It is actually the same as
JacksonJsonRedisSerializer JacksonJsonRedisSerializer: Serializes object to json string
JdkSerializationRedisSerializer: Serialize java objects
StringRedisSerializer: Simple string serialization.

Generally, if the key-value is string, you can use StringRedisSerializer. If you need to save the object as json, it is recommended to use JacksonJsonRedisSerializer. It can not only serialize objects, but also The object is converted to a json string and saved to redis, but it needs to be used together with jackson.
A simple redis operation
code example is as follows, using redis for set and get operations.
MyUserRepository.java
@Repository
public class MyUserRepository {
  //You can directly use autowire to reference the redis-template in the configuration file
    @Autowired
    private RedisTemplate<String, MyUser> template;

    private ValueOperations<String, MyUser> operations;

    @PostConstruct
    public void init() {
      //Set the serialization method of value here to JacksonJsonRedisSerializer
        template.setValueSerializer(new JacksonJsonRedisSerializer<>(MyUser.class));
        operations = template.opsForValue();
    }

    public void set(String key, MyUser value) {
        operations.set(key, value);
    }

    public MyUser get(String key) {
        return operations.get(key);
    }
}

// model
public class MyUser {
    private String username;
    private int age;
    // ... setter and getter
}

// Called in Controller
@Controller
public class MainController {

    @Autowired
    private MyUserRepository myUserRepository;

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public
    @ResponseBody
    ResponseEntity<?> test() throws Exception {
        MyUser user = new MyUser("zhaozhiming", 100);
        String key = "my:user:zhaozhiming";
        myUserRepository.set(key, user);
        MyUser myUser = myUserRepository.get(key);
        log.debug(String.format("my user:%s", myUser));
        String result = mapper.writeValueAsString(user);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
}

After calling the set method, you can see the MyUser object after get in the log.
- my user:MyUser{age=100, username='zhaozhiming'}
can also see the saved json string in redis. A tool class: RedisUtil is an instance used to cache and remove data . If it is not necessary, please change it to private RedisTemplate<String, Object> redisTemplate;







package com.pandy.framework.base.redis.utils;

/**
 * Created by pandy on 16-5-3.
 */

import org.apache.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis cache tool class
 *
 */
public final class RedisUtil {
    private Logger logger = Logger.getLogger (RedisUtil.class);
    private RedisTemplate<Serializable, Object> redisTemplate;

    /**
     * Batch delete the corresponding value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * Batch delete keys
     *
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }

    /**
     * delete the corresponding value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * Determine whether there is a corresponding value in the cache
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * read cache
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    public <T> T get(final String key, Class<T> t) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return (T)result;
    }

    /**
     * write cache
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return result;
    }

    /**
     * write cache
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return result;
    }

    public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326984349&siteId=291194637