【问题标题】:spring boot use redisTemplate to decr stockspring boot 使用 redisTemplate 来decr stock
【发布时间】:2016-11-18 00:01:20
【问题描述】:

我想比较mysqlredis 存储中的并发递减产品库存,我发现找到spring boot + redisTemplate 的一些演示并不容易,从我在下面的代码中编写的一些文档到decr 库存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/

【问题讨论】:

    标签: redis spring-boot


    【解决方案1】:
    Long stock = redisTemplate.opsForValue().increment("1_stock", -1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-19
      • 2014-05-15
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      相关资源
      最近更新 更多