我想比较mysql
和redis
存储空间中的并发减量产品库存,我发现从某些文档中找到spring boot + redisTemplate
的某些演示并不容易我将以下代码写入了redis的decr
股票
@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/
答案 0 :(得分:0)
Long stock = redisTemplate.opsForValue().increment("1_stock", -1);