您的位置:首页 > 数据库 > Redis

关于如何从Redis中取出自增值的方法

2018-01-11 20:18 120 查看
此方法适用于想要从redis中获取一个全局(分布式)唯一的数字,一般结合时间戳使用,可以拼接在一起作为一个本机唯一标识.代码如下:(测试代码也在后面)

package *****;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.kinglong.p2p.constant.Constant;

/**
* redis全剧唯一数字业务实现类
*ClassName:UniqueRedisNumberServiceImpl
*<p>Desc:</p>
* @author
*/
@Service
public class UniqueRedisNumberServiceImpl implements UniqueRedisNumberService {

@Autowired
private RedisTemplate<String, Serializable> redisTemplate;

/**
* 获取redis全局唯一数字
*/
@Override
public long getUniqueRedisNumber() {

//注意:1L表示取得的值为长整型,并且他们是每次递增1个.如果为2L,则表示每次递增2

long result = redisTemplate.opsForValue().increment(Constant.UNIQUE_NUMBER,1L);

return result;
}
}


//测试代码

package ***;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.kinglong.p2p.service.loan.BidInfoService;
import com.kinglong.p2p.service.loan.UniqueRedisNumberService;
public class Test02 {
public static void main(String[] args) {
//加载spring框架容器是测试方法的核心,一定不能漏了
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
BidInfoService bidInfoService = (BidInfoService) context.getBean("bidInfoServiceImpl");
UniqueRedisNumberService uniqueRedisNumberService = (UniqueRedisNumberService) context.getBean("uniqueRedisNumberServiceImpl");
//准备请求参数
long uniqueRedisNumber = uniqueRedisNumberService.getUniqueRedisNumber();

System.out.println(uniqueRedisNumber);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: