您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Spring Data Redis的示例分析
## 1. 引言
Redis作为高性能的键值存储系统,在现代分布式系统中扮演着重要角色。Spring Data Redis通过提供模板模式和Repository支持,显著简化了Java应用与Redis的交互。本文将结合代码示例,深入分析其核心功能和使用模式。
## 2. 环境配置
### 2.1 依赖引入
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
spring:
redis:
host: localhost
port: 6379
password:
jedis:
pool:
max-active: 8
max-wait: -1ms
作为核心操作类,提供类型安全的操作方式:
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
序列化方式 | 特点 | 适用场景 |
---|---|---|
StringRedisSerializer | 字符串专用 | 简单键值存储 |
Jackson2JsonRedisSerializer | JSON格式 | 复杂对象存储 |
JdkSerializationRedisSerializer | Java原生序列化 | 不推荐(有安全风险) |
@Autowired
private ValueOperations<String, String> valueOps;
public void basicOperations() {
valueOps.set("current_time", LocalDateTime.now().toString());
String time = valueOps.get("current_time");
valueOps.increment("counter", 1L);
}
@Autowired
private HashOperations<String, String, Object> hashOps;
public void userProfileDemo() {
Map<String, Object> profile = new HashMap<>();
profile.put("name", "John");
profile.put("age", 30);
hashOps.putAll("user:1001", profile);
Object age = hashOps.get("user:1001", "age");
}
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory factory,
MessageListenerAdapter listener) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(factory);
container.addMessageListener(listener, new ChannelTopic("news"));
return container;
}
public class Receiver {
public void handleMessage(String message) {
System.out.println("Received: " + message);
}
}
public void transferFunds(String from, String to, double amount) {
redisTemplate.execute(new SessionCallback<>() {
@Override
public Object execute(RedisOperations operations) {
operations.watch(from);
operations.watch(to);
double balance = Double.parseDouble(operations.opsForValue().get(from));
if (balance >= amount) {
operations.multi();
operations.opsForValue().decrement(from, amount);
operations.opsForValue().increment(to, amount);
return operations.exec();
}
return null;
}
});
}
@Cacheable(value = "products", key = "#id")
public Product getProductById(String id) {
// 数据库查询逻辑
}
@CacheEvict(value = "products", key = "#id")
public void updateProduct(Product product) {
// 更新逻辑
}
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.disableCachingNullValues();
return RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
}
List<Object> results = redisTemplate.executePipelined(...);
DefaultRedisScript<Long> script = new DefaultRedisScript<>(luaCode, Long.class);
redisTemplate.execute(script, keys, args);
redis-cli info memory
Spring Data Redis通过抽象化的API和丰富的功能集成,使开发者能够高效利用Redis的各项特性。本文展示的示例涵盖了从基础操作到高级应用的典型场景,实际开发中应根据具体需求选择合适的操作模式,并注意性能优化和异常处理。
最佳实践提示:生产环境建议配置哨兵或集群模式,并实现健康检查机制。 “`
(注:实际字符数约1580字,可根据需要调整具体章节内容)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。