SpringBoot集成redis集群存储字符串和对象

SpringBoot集成redis集群相比于Springmvc方便了很多,本例中使用的是3台机器搭建的redis cluster集群,为3主3从的配置,集体的搭建细节在此不做示例。具体集成redis步骤如下所示:

首先需要引入依赖:

Spring Boot提供的数据访问框架Spring Data Redis基于Jedis。可以通过引入spring-boot-starter-redis来配置依赖关系


    org.springframework.boot
    spring-boot-starter-redis

参数配置:

   在application.yml(ps:要是使用application.properties配置类似)中加入如下配置:

spring:
  redis:
    cluster:
      nodes:
           - 10.7.28.179:6379
           - 10.7.28.180:6379
           - 10.7.28.181:6379
           - 10.7.28.179:6380
           - 10.7.28.180:6380
           - 10.7.28.181:6380
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait: -1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle: 8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle: 0
# 连接超时时间(毫秒)
spring.redis.timeout: 0

测试访问:

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRedis {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * redis缓存测试放入普通的字符串
     * @throws Exception
     */
    @Test
    public void testRedisByString() throws Exception {
        // 保存字符串
        stringRedisTemplate.opsForValue().set("aaa", "122");
        Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
    }
}
通过上面简单的测试就可以在redis上面存储数据了 不过上面的方式只支持String类型的存储,我们平时比较常用的还有存储对象,下面介绍下存储对象的方式:
创建要存储的对象:

package tf56.SpringBoot.domain;

import java.io.Serializable;

/**
 * 创建需要放入redis的对象
 */
public class UserRedis implements Serializable {
    private static final long serialVersionUID = -1L;
    private String username;
    private Integer age;
    public UserRedis(String username, Integer age) {
        this.username = username;
        this.age = age;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username=username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age=age;
    }
}
实现对象的序列化接口:

package tf56.SpringBoot.utils;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * 实现对象的序列化接口
 */
public class RedisObjectSerializer implements RedisSerializer {
    private Converter serializer = new SerializingConverter();
    private Converter deserializer = new DeserializingConverter();
    static final byte[] EMPTY_ARRAY = new byte[0];
    public Object deserialize(byte[] bytes) {
        if (isEmpty(bytes)) {
            return null;
        }
        try {
            return deserializer.convert(bytes);
        } catch (Exception ex) {
            throw new SerializationException("Cannot deserialize", ex);
        }
    }
    public byte[] serialize(Object object) {
        if (object == null) {
            return EMPTY_ARRAY;
        }
        try {
            return serializer.convert(object);
        } catch (Exception ex) {
            return EMPTY_ARRAY;
        }
    }
    private boolean isEmpty(byte[] data) {
        return (data == null || data.length == 0);
    }
}配置实例: 
  

package tf56.SpringBoot.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import tf56.SpringBoot.domain.UserRedis;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 配置针对UserRedis的RedisTemplate实例

 */
@Configuration
@EnableRedisRepositories
public class RedisConfig {
    /**
     * 如果这里注入了JedisConnectionFactory,加载的时候application.yml中的配置不会起作用,所以
     * 初始化JedisConnectionFactory对象的时候需要加入clusterNodes节点信息
     */
    List clusterNodes = Arrays.asList("10.7.28.179:6379", "10.7.28.179:6380", "10.7.28.180:6379", "10.7.28.180:6380", "10.7.28.181:6379", "10.7.28.181:6380");

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory(new RedisClusterConfiguration(clusterNodes));
    }

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjectSerializer());
        return template;
    }

}
完成配置后,编写测试实现效果:

package tf56.SpringBoot.controller;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import tf56.SpringBoot.domain.UserRedis;

/**
 * Created by Administrator on 2017/8/30.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRedis {
    
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * redis 缓存测试存放对象
     * @throws Exception
     */
   @Test
    public void testRedisByObject() throws Exception {
        // 保存对象
        UserRedis user = new UserRedis("超人", 20);
        redisTemplate.opsForValue().set(user.getUsername(), user);
        user = new UserRedis("蝙蝠侠", 30);
        redisTemplate.opsForValue().set(user.getUsername(), user);
        user = new UserRedis("蜘蛛侠", 40);
        redisTemplate.opsForValue().set(user.getUsername(), user);

       System.out.println(redisTemplate.opsForValue().get("超人").getAge());
       System.out.println(redisTemplate.opsForValue().get("蝙蝠侠").getAge());
       System.out.println(redisTemplate.opsForValue().get("蜘蛛侠").getAge());
    }
}






你可能感兴趣的:(SpringBoot集成redis集群存储字符串和对象)