gpt4 book ai didi

redis - spring boot 使用 redisTemplate 减少库存

转载 作者:可可西里 更新时间:2023-11-01 11:35:03 25 4
gpt4 key购买 nike

我想比较mysqlredis存储中的并发递减积存量,发现spring boot + redisTemplate的demo不太好找,从我在下面写的一些文档到 decr stock in redis

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

@Bean
RedisTemplate<String, Long> redisTemplate() {
final RedisTemplate<String, Long> template = new RedisTemplate<String, Long>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericToStringSerializer<Long>(Long.class));
template.setValueSerializer(new GenericToStringSerializer<Long>(Long.class));
return template;
}


private Callable<Void> updateStockInRedisTask = () -> {
redisTemplate().execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
Long decr = connection.decr("1_stock".getBytes());
return decr;
}
});
return null;
};

可以用,但我觉得有点麻烦,尤其是和jdbcTemplate相比,请看下面

@Autowired
private JdbcTemplate jdbcTemplate;

private Callable<Void> updateStockInMysqlTask = () -> {
final String sql = "update product_stock set stock = stock-1 where award_id=1 and stock>0";
jdbcTemplate.update(sql);
return null;
};

所以我想知道是否可以简化它?

顺便说一句我引用了这些文档:

How autowired RedisTemplate<String,Long>

http://docs.spring.io/spring-data/redis/docs/current/reference/html/

最佳答案

Long stock = redisTemplate.opsForValue().increment("1_stock", -1);

关于redis - spring boot 使用 redisTemplate 减少库存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35958675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com