0

I want to compare concurrent decrement product stock in mysql and redis storage, and I found it's not very easy to find some demo for spring boot + redisTemplate, from some docs I wrote below code to 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;
};

and it works, but I think it's a little cumbersome, especially compared with jdbcTemplate, please see below

@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;
};

So I'd like to know if it could be simplified?

BTW I refered these docs:

How autowired RedisTemplate<String,Long>

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

Community
  • 1
  • 1
zhuguowei
  • 8,401
  • 16
  • 70
  • 106

1 Answers1

0
Long stock = redisTemplate.opsForValue().increment("1_stock", -1);
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140