Spring Boot 之 Redis
Spring Boot 之 Redis集成
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Redis服务器连接配置
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口号
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1ms
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.shutdown-timeout=100ms
创建Redis配置类
package com.icodesoft.springboot.redis;
import com.icodesoft.springboot.redis.domain.User;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {
@Bean
public RedisTemplate<String, User> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, User> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new RedisObjectSerializer());
return redisTemplate;
}
import redis.clients.jedis.JedisPool;
@Bean
public JedisPool jedisPool(JedisPoolConfig jedisPoolConfig, RedisStandaloneConfiguration jedisConfig) {
JedisPoolConfig jedisPoolConfig2 = new JedisPoolConfig();
// jedisPoolConfig.setMaxIdle(100);
jedisPoolConfig2.setMaxWaitMillis(6000);
jedisPoolConfig2.setMaxTotal(100);
// jedisPoolConfig.setMinIdle(pool.getMinIdle());
// jedisPoolConfig.setTestOnCreate(pool.getTestOnCreate());
// jedisPoolConfig.setTestOnBorrow(pool.getTestOnBorrow());
// jedisPoolConfig.setTestOnBorrow(pool.getTestOnReturn());
// jedisPoolConfig.setTestWhileIdle(pool.getTestWhileIdle());
JedisPool jedisPool = new JedisPool(jedisPoolConfig2, jedisConfig.getHostName(), jedisConfig.getPort(), 12000);
return jedisPool;
}
private JedisPool jedisPool;
@Override
@ExecuteTime
public Long checkRedis() {
log.info("check redis service health");
log.info("pool NumActive: " + jedisPool.getNumActive());
try (Jedis jedis = jedisPool.getResource()) {
jedis.ping();
}
log.info("redis service is online");
return 0L;
}
// 仅使用于jedis的使用场景
// @Bean
// public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPool,
// RedisStandaloneConfiguration jedisConfig) {
// JedisConnectionFactory connectionFactory = new JedisConnectionFactory(jedisConfig);
// connectionFactory.setPoolConfig(jedisPool);
// return connectionFactory;
// }
//
// @Configuration
// public static class JedisPoolConf {
// @Value("${spring.redis.host:127.0.0.1}")
// private String host;
// @Value("${spring.redis.port:6379}")
// private Integer port;
// @Value("${spring.redis.password:}")
// private String password;
// @Value("${spring.redis.database:0}")
// private Integer database;
//
// @Value("${spring.redis.jedis.pool.max-active:8}")
// private Integer maxActive;
// @Value("${spring.redis.jedis.pool.max-idle:8}")
// private Integer maxIdle;
// @Value("${spring.redis.jedis.pool.max-wait:-1}")
// private Long maxWait;
// @Value("${spring.redis.jedis.pool.min-idle:0}")
// private Integer minIdle;
//
// @Bean
// public JedisPoolConfig jedisPool() {
// JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// jedisPoolConfig.setMaxIdle(maxIdle);
// jedisPoolConfig.setMaxWaitMillis(maxWait);
// jedisPoolConfig.setMaxTotal(maxActive);
// jedisPoolConfig.setMinIdle(minIdle);
// return jedisPoolConfig;
// }
//
// @Bean
// public RedisStandaloneConfiguration jedisConfig() {
// RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
// config.setHostName(host);
// config.setPort(port);
// config.setDatabase(database);
// config.setPassword(RedisPassword.of(password));
// return config;
// }
// }
}
创建类序列化与反序列化类RedisObjectSerializer.java
package com.icodesoft.springboot.redis;
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];
@Override
public byte[] serialize(Object o) throws SerializationException {
if (o == null) {
return EMPTY_ARRAY;
}
try {
return serializer.convert(o);
} catch (Exception ex) {
return EMPTY_ARRAY;
}
}
@Override
public Object deserialize(byte[] bytes) throws SerializationException {
if (isEmpty(bytes)) {
return null;
}
try {
return deserializer.convert(bytes);
} catch (Exception ex) {
throw new SerializationException("Cannot deserialize", ex);
}
}
private boolean isEmpty(byte[] data) {
return (data == null || data.length == 0);
}
}
创建实体类User
package com.icodesoft.springboot.redis.domain;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = -1L;
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public User() {
}
}
测试
记得运行前开启redis服务哈
package com.icodesoft.springboot.redis;
import com.icodesoft.springboot.redis.domain.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Assert;
@SpringBootTest
class RedisApplicationTests {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String, User> userRedisTemplate;
@Test
void contextLoads() {
BoundValueOperations<String, String> boundValueOps = this.stringRedisTemplate.boundValueOps("myname");
Assert.isTrue(boundValueOps.get().equals("gary"), "获取myname值时失败");
User user = new User("gao", 22);
this.userRedisTemplate.opsForValue().set(user.getName(), user);
User result = this.userRedisTemplate.boundValueOps(user.getName()).get();
System.out.println(user.getAge() + "***************Age: " + result.getAge());
Assert.isTrue(user.getAge().equals(result.getAge()), "获取数据错误");
}
}


浙公网安备 33010602011771号