java结合mysql实现计数器_java – 全局内存计数器,它是线程安全的,并且每x个增量刷新到mysql...

康斯坦丁说,像redis这样的东西可能是更好的解决方案. Cassandra专柜也是做这类事情的好方法.

如果你想用java做这个,这里有一些代码可以安全地增加计数而不会阻塞,

class Counter {

private final ConcurrentHashMap counts = new ConcurrentHashMap();

//increment the count for the user

public void increment(String user) {

while(true) {

AtomicInteger current = counts.get(user);

if(current == null) {

//new user, initialize the count

counts.putIfAbsent(user, new AtomicInteger());

continue;

}

int value = current.incrementAndGet();

if(value > 0) {

//we have incremented the counter

break;

} else {

//someone is flushing this key, remove it

//so we can increment on our next iteration

counts.replace(user, current, new AtomicInteger());

}

}

}

//call this periodically to flush keys to the database

//this will empty the counts map so that users who

//are not active do not take up space

public void flush() {

Map toFlush = new HashMap();

for(Map.Entry entry : counts.entrySet()) {

String user = entry.getKey();

AtomicInteger currentCount = entry.getValue();

//stop incrementing this count

counts.remove(user, currentCount);

//if someone is trying to increment this AtomicInteger after

//we remove it, they will see a -ve value from incrementAndGet, and

//will know their increment did not succeed

Integer count = currentCount.getAndSet(Integer.MIN_VALUE);

toFlush.put(user, count);

}

for(Map.Entry clearedEntry : toFlush.entrySet()) {

writeToDb(clearedEntry.getKey(), clearedEntry.getValue());

}

}

public void writeToDb(String user, int count) {

//do something with the count here

}

}

代码相当复杂,正如Peter Lawrey所说,使用synchronized关键字保护的简单映射可能性能足够好并且更易于维护.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值