SpringBoot集成redis集群存储字符串和对象
2017-08-31 12:28
701 查看
SpringBoot集成redis集群相比于Springmvc方便了很多,本例中使用的是3台机器搭建的redis cluster集群,为3主3从的配置,集体的搭建细节在此不做示例。具体集成redis步骤如下所示:
首先需要引入依赖:
Spring Boot提供的数据访问框架Spring Data Redis基于Jedis。可以通过引入spring-boot-starter-redis来配置依赖关系
参数配置:
在application.yml(ps:要是使用application.properties配置类似)中加入如下配置:
测试访问:
@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<Object> {
private Converter<Object, byte[]> serializer = new SerializingConverter();
private Converter<byte[], Object> 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<String> 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<String, UserRedis> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, UserRedis> template = new RedisTemplate<String, UserRedis>();
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<String, UserRedis> 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());
}
}
首先需要引入依赖:
Spring Boot提供的数据访问框架Spring Data Redis基于Jedis。可以通过引入spring-boot-starter-redis来配置依赖关系
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
参数配置:
在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<Object> {
private Converter<Object, byte[]> serializer = new SerializingConverter();
private Converter<byte[], Object> 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<String> 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<String, UserRedis> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, UserRedis> template = new RedisTemplate<String, UserRedis>();
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<String, UserRedis> 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());
}
}
相关文章推荐
- Springboot2.X集成redis集群(Lettuce)连接的方法
- springboot集成redis集群(带密码并序列化)
- IDEA springboot集成ehcache单节点和redis集群
- 服务器入门:docker下的集群操作,docker+nginx+springboot+redis+mysql。
- Spring-Data-Redis存储对象(redisTemplate)
- springboot 集成 redis 持久化缓存
- 在SpringBoot中集成Redis
- Maven中Spring-Data-Redis存储对象(redisTemplate)
- SpringBoot实践之---集成Redis
- Spring Boot 2.0.0.M7 使用Spring Session实现集群-redis
- spring boot下JedisCluster方式连接Redis集群的配置
- 使用Spring-Data-Redis存储对象(redisTemplate)
- Spring集成Redis集群(含spring集成redis代码)
- 关于Spring boot 与 redis 的集成,以及Spring中redis的使用
- springboot集成redis做缓存
- Redis 存储字符串和对象
- Maven中Spring-Data-Redis存储对象(redisTemplate)
- springboot 集成redis (单点)
- spring-boot集成redis单机版
- Spring Boot集成Shiro并利用MongoDB做Session存储的方法详解