博客
关于我
springboot2.0整合Jedis
阅读量:796 次
发布时间:2023-03-22

本文共 3292 字,大约阅读时间需要 10 分钟。

Spring Boot Redis配置示例

1. 依赖管理

在Spring Boot项目中,Redis依赖需要通过Maven仓库添加。以下是推荐的依赖配置:

org.springframework.boot
spring-boot-starter-data-redis
2.0.0
redis.clients
jedis
io.lettuce
lettuce-core
redis.clients
jedis
2.8.0
com.alibaba
fastjson
1.2.47

注意:1.5版本的Spring Boot Redis依赖与2.0版本存在差异,特别是连接池技术的选择。这里使用jedis作为连接池,默认情况下会替换lettuce。

2. Redis配置

spring:
redis:
host: 172.30.66.104
port: 6379
password: 19e.com.cn
database: 0
jedis:
pool:
max-active: 5
max-idle: 10
min-idle: 0

3. RedisTemplate配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {
@Bean
public RedisTemplate
redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate
template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// JSON序列化
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
// 字符串序列化
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
}

4. 测试示例

import com.qwe.common.demo.User;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void redisTest() {
// 存储字符串
String key = "name";
redisTemplate.opsForValue().set(key, "qwe");
// 获取字符串
String value = (String) redisTemplate.opsForValue().get(key);
System.out.println("key: " + key + ", value: " + value);
// 存储对象
User user = new User("qw", 12);
String userKey = "qwe";
redisTemplate.opsForValue().set(userKey, user);
// 获取对象
User newUser = (User) redisTemplate.opsForValue().get(userKey);
System.out.println("key: " + userKey + ", value: " + newUser);
}
}

以上配置和示例可根据实际项目需求进行调整,确保Redis服务器配置正确并且权限设置适当。

转载地址:http://jtqfk.baihongyu.com/

你可能感兴趣的文章