Java操作Redis数据
Redis 是完全开源免费的,遵守BSD协议,先进的key - value持久化产品。它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Map),列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。下面是使用spring-data-redis分别针对key和value的操作。
1.Key(键)
-
public class KeysTest extends RedisCommon {
-
private static StringRedisTemplate template;
-
private static String key = "key1";
-
-
public static void main(String[] args) {
-
log.info("-----------Starting Redis keys testing-----------");
-
ApplicationContext ctx = SpringApplication.run(KeysTest.class, args);
-
template = ctx.getBean(StringRedisTemplate.class);
-
KeysTest keysTest = ctx.getBean(KeysTest.class);
-
keysTest.initValue();
-
-
log.info("KeysTest @##@ randomKey: " + template.randomKey());
-
-
keysTest.expireKey(key, 2);
-
// keysTest.persistKey(key, 2);
-
-
String newkey = "newKey";
-
// template.rename(key, newkey);
-
template.renameIfAbsent(key, newkey);
-
-
Set<String> keys = template.keys("*");
-
log.info("KeysTest @##@ keys:" + keys);
-
for (String key : keys) {
-
log.info("KeysTest @##@ " + key + " expire:"
-
+ template.getExpire(key));
-
// template.getExpire(key, TimeUnit.SECONDS);
-
}
-
-
int dbIndex = 1;// ref:http://redisdoc.com/key/move.html
-
log.info("KeysTest @##@ move " + key + " to db" + dbIndex + ": "
-
+ template.move(key, 1));
-
-
// template.delete(key);
-
template.delete(keys);
-
log.info("KeysTest @##@ delete keys: " + keys);
-
-
// template.exec();
-
// template.multi();
-
// template.discard();
-
-
// template.slaveOf(host, port);
-
// template.slaveOfNoOne();
-
-
// template.watch(key);
-
// template.watch(keys);
-
// template.unwatch();
-
log.info("-----------End Redis keys testing-----------");
-
}
-
-
public void initValue() {
-
String value = "hello,redis";
-
template.opsForValue().set(key, value);
-
Set<String> keys = new HashSet<String>() {
-
private static final long serialVersionUID = -4402948387930279259L;
-
{
-
this.add("key2");
-
this.add("key3");
-
this.add("key4");
-
}
-
};
-
try {
-
byte[] bytes = template.dump(key);
-
log.info("KeysTest # key dump:" + new String(bytes));
-
for (String k : keys) {
-
template.restore(k, bytes, 0, TimeUnit.SECONDS);
-
}
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
}
-
-
public boolean expireKey(String key, long expiretime) {
-
log.info("KeysTest @##@ has " + key + " : " + template.hasKey(key));
-
log.info("KeysTest @##@ expire " + key + " for " + expiretime
-
+ " seconds : "
-
+ template.expire(key, expiretime, TimeUnit.SECONDS));
-
// template.expireAt(key, new Date());
-
try {
-
Thread.sleep((expiretime + 1) * 1000);
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
boolean result = template.hasKey(key);
-
log.info("KeysTest @##@ has " + key + " : " + result);
-
return result;
-
}
-
-
public boolean persistKey(String key, long expiretime) {
-
log.info("KeysTest @##@ has " + key + " : " + template.hasKey(key));
-
log.info("KeysTest @##@ expire " + key + " for " + expiretime
-
+ " seconds : "
-
+ template.expire(key, expiretime, TimeUnit.SECONDS));
-
log.info("KeysTest @##@ persist " + key + " : " + template.persist(key));
-
try {
-
Thread.sleep((expiretime + 1) * 1000);
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
return template.hasKey(key);
-
}
-
-
}
2.String(字符串)
-
public class StringsTest extends RedisCommon {
-
private static StringRedisTemplate template;
-
private static String key = "strKey";
-
-
public static void main(String[] args) throws InterruptedException {
-
log.info("-----------Starting Redis Strings testing-----------");
-
ApplicationContext ctx = SpringApplication.run(StringsTest.class, args);
-
template = ctx.getBean(StringRedisTemplate.class);
-
StringsTest stringsTest = ctx.getBean(StringsTest.class);
-
-
String value = "hello, redis";
-
template.opsForValue().set(key, value);
-
log.info("StringsTest @##@ " + key + "'s value: " + template.opsForValue().get(key));
-
log.info("StringsTest @##@ " + key + "'s size: " + template.opsForValue().size(key));
-
-
stringsTest.getRange(key, 0, 5);
-
-
template.opsForValue().getAndSet(key, "hello, redis world");
-
log.info("StringsTest @##@ " + key + "'s value after getAndSet: " + template.opsForValue().get(key));
-
-
stringsTest.multiOperation();
-
-
stringsTest.incrementDouble();
-
-
stringsTest.incrementLong();
-
}
-
-
public void getRange(String key, int start, int end){
-
log.info("StringsTest @##@ " + key + "'s value: " + template.opsForValue().get(key));
-
log.info("StringsTest @##@ " + key + " range from "+start +" to " + end +" value is: " + template.opsForValue().get(key, start, end));
-
}
-
-
public void multiOperation(){
-
Map<String, String> m = new HashMap<>();
-
Set<String> keys = new HashSet<>();
-
for(int i=0;i< 4;i++){
-
m.put("key" + i, "value" + i);
-
keys.add("key" + i);
-
}
-
template.opsForValue().multiSet(m);
-
log.info("StringsTest @##@ multiSet : done.");
-
log.info("StringsTest @##@ multiGet : " + template.opsForValue().multiGet(keys));
-
}
-
-
public void incrementDouble() {
-
String hashKey = UUID.randomUUID().toString();
-
Double value1 = template.opsForValue().increment(hashKey, 30.5d);
-
log.info(hashKey + " has value :" + value1);
-
double d = 30.2d;
-
Double value2 = template.opsForValue().increment(hashKey, d);
-
log.info(hashKey + " has value: " + value2 + ", after increment " + d);
-
}
-
-
public void incrementLong() {
-
String hashKey = UUID.randomUUID().toString();
-
long value1 = template.opsForValue().increment(hashKey, 30l);
-
log.info(hashKey + " has value :" + value1);
-
long l = 25l;
-
long value2 = template.opsForValue().increment(hashKey, l);
-
log.info(hashKey + " has value: " + value2 + ", after increment " + l);
-
}
-
}
3.Hash(哈希表)
-
public class HashTest extends RedisCommon {
-
private static RedisTemplate<String, Map<String, UserInfo>> userTemplate;
-
private static RedisTemplate<String, Map<String, Double>> doubleTemplate;
-
private static RedisTemplate<String, Map<String, Long>> longTemplate;
-
private static String key = "UserInfo";
-
-
public static void main(String[] args) throws InterruptedException {
-
log.info("-----------Starting Redis hash testing-----------");
-
ApplicationContext ctx = SpringApplication.run(HashTest.class, args);
-
RedisConnectionFactory connectionFactory = ctx
-
.getBean(RedisConnectionFactory.class);
-
userTemplate = new RedisTemplate<>();
-
userTemplate.setConnectionFactory(connectionFactory);
-
userTemplate.setKeySerializer(userTemplate.getStringSerializer());
-
userTemplate.setHashKeySerializer(userTemplate.getStringSerializer());
-
userTemplate
-
.setHashValueSerializer(new JacksonJsonRedisSerializer<UserInfo>(
-
UserInfo.class));
-
userTemplate.afterPropertiesSet();
-
-
doubleTemplate = new RedisTemplate<>();
-
doubleTemplate.setConnectionFactory(connectionFactory);
-
doubleTemplate.setKeySerializer(doubleTemplate.getStringSerializer());
-
doubleTemplate.setHashKeySerializer(doubleTemplate.getStringSerializer());
-
doubleTemplate.setHashValueSerializer(doubleTemplate.getDefaultSerializer());
-
doubleTemplate.afterPropertiesSet();
-
-
longTemplate = new RedisTemplate<>();
-
longTemplate.setConnectionFactory(connectionFactory);
-
longTemplate.setKeySerializer(longTemplate.getStringSerializer());
-
longTemplate.setHashKeySerializer(longTemplate.getStringSerializer());
-
longTemplate.setHashValueSerializer(new LongSerializer());
-
longTemplate.afterPropertiesSet();
-
-
HashTest hashTest = ctx.getBean(HashTest.class);
-
// hashTest.insert();
-
// hashTest.batchInsert();
-
// hashTest.insertIfAbsent();
-
// hashTest.findAll();
-
// hashTest.findOne();
-
// hashTest.findAllKeys();
-
// hashTest.incrementDouble();
-
hashTest.incrementLong();
-
}
-
-
public void insert() {
-
UserInfo info = new UserInfo();
-
info.setName("Tomy");
-
info.setAge(20);
-
info.setBirthday(new Date());
-
info.setId(UUID.randomUUID().toString());
-
userTemplate.opsForHash().put(key, info.getId(), info);
-
log.info("insert User[" + info + "] success!");
-
log.info("User Hash size is : " + userTemplate.opsForHash().size(key));
-
}
-
-
public void batchInsert() {
-
Map<String, UserInfo> users = new HashMap<>();
-
for (int i = 1; i <= 3; i++) {
-
UserInfo info = new UserInfo();
-
info.setName("Tomy" + i);
-
info.setAge(20 + i);
-
info.setBirthday(new Date());
-
info.setId(UUID.randomUUID().toString());
-
users.put(info.getId(), info);
-
}
-
userTemplate.opsForHash().putAll(key, users);
-
log.info("batchInsert Users[" + users + "] success!");
-
log.info("User Hash size is : " + userTemplate.opsForHash().size(key));
-
}
-
-
public void insertIfAbsent() {
-
UserInfo info = new UserInfo();
-
info.setName("Tomy4");
-
info.setAge(20);
-
info.setBirthday(new Date());
-
info.setId(UUID.randomUUID().toString());
-
userTemplate.opsForHash().putIfAbsent(key, info.getId(), info);
-
log.info("insertIfAbsent User[" + info + "] success!");
-
log.info("User Hash size is : " + userTemplate.opsForHash().size(key));
-
}
-
-
public void findAll() {
-
Map<Object, Object> users = userTemplate.opsForHash().entries(key);
-
log.info("All User[" + users + "]");
-
log.info("findAll User size is : " + users.size());
-
}
-
-
public UserInfo findOne() {
-
String hashKey = "2ca66275-88ab-49e5-8651-b987e55d9347";
-
Object userInfo = userTemplate.opsForHash().get(key, hashKey);
-
// boolean have = userTemplate.opsForHash().hasKey(hashKey, hashKey);
-
log.info("find one : " + userInfo);
-
return userInfo != null ? (UserInfo) userInfo : null;
-
}
-
-
public Set<Object> findAllKeys() {
-
Set<Object> users = userTemplate.opsForHash().keys(key);
-
log.info("find : " + users.size() + " users :" + users);
-
return users;
-
}
-
-
public void scan() {
-
userTemplate.opsForHash().scan(key, ScanOptions.NONE);
-
}
-
-
public void incrementDouble() {
-
String hashKey = UUID.randomUUID().toString();
-
Double value1 = doubleTemplate.opsForHash().increment(key, hashKey,
-
Double.valueOf("30"));
-
log.info(key + ":" + hashKey + " has value :" + value1);
-
Double delta = Double.valueOf("30.3");
-
Double value2 = doubleTemplate.opsForHash().increment(key, hashKey, delta);
-
log.info(key + ":" + hashKey + " has value: " + value2 + ", after increment " + delta);
-
}
-
-
public void incrementLong() {
-
String hashKey = UUID.randomUUID().toString();
-
long value1 = doubleTemplate.opsForHash().increment(key, hashKey, 30l);
-
log.info(key + ":" + hashKey + " has value :" + value1);
-
long delta = 20l;
-
long value2 = doubleTemplate.opsForHash().increment(key, hashKey, delta);
-
log.info(key + ":" + hashKey + " has value: " + value2 + ", after increment " + delta);
-
}
-
-
}
4.List(列表)
-
public class ListsTest extends RedisCommon {
-
private static RedisTemplate<String, UserInfo> userTemplate;
-
-
public static void main(String[] args) throws InterruptedException {
-
log.info("-----------Starting Redis Lists testing-----------");
-
ApplicationContext ctx = SpringApplication.run(ListsTest.class, args);
-
RedisConnectionFactory connectionFactory = ctx
-
.getBean(RedisConnectionFactory.class);
-
userTemplate = new RedisTemplate<>();
-
userTemplate.setConnectionFactory(connectionFactory);
-
userTemplate.setKeySerializer(userTemplate.getStringSerializer());
-
userTemplate.setValueSerializer(new JacksonJsonRedisSerializer<UserInfo>(
-
UserInfo.class));
-
userTemplate.afterPropertiesSet();
-
-
String key = "UserInfo";
-
-
ListsTest listsTest = ctx.getBean(ListsTest.class);
-
listsTest.leftpush(key);
-
listsTest.leftpushBatch(key);
-
listsTest.leftpop(key);
-
listsTest.rightPopAndLeftPush(key);
-
}
-
-
public void leftpush(String key) {
-
int size = 10;
-
for(int i = 0; i < size; i++){
-
UserInfo info = new UserInfo();
-
info.setName("Tomy" + i);
-
info.setAge(20 + i);
-
info.setBirthday(new Date());
-
info.setId(UUID.randomUUID().toString());
-
userTemplate.opsForList().leftPush(key, info);
-
//userTemplate.opsForList().leftPush(key, pivot, value)
-
//userTemplate.opsForList().leftPushIfPresent(key, value)
-
//userTemplate.opsForList().rightPush(key, pivot, value)
-
//userTemplate.opsForList().rightPushIfPresent(key, value)
-
}
-
log.info("insert [" + size + "] User success! " + key + "'s size is:" + userTemplate.opsForList().size(key));
-
}
-
-
public void leftpushBatch(String key){
-
int size = 20;
-
List<UserInfo> users = new ArrayList<>();
-
for(int i = 10; i < size; i++){
-
UserInfo info = new UserInfo();
-
info.setName("Tomy" + i);
-
info.setAge(20 + i);
-
info.setBirthday(new Date());
-
info.setId(UUID.randomUUID().toString());
-
users.add(info);
-
}
-
userTemplate.opsForList().leftPushAll(key, users.toArray(new UserInfo[users.size()]));
-
//userTemplate.opsForList().rightPushAll(key, (UserInfo[])users.toArray());
-
log.info("batchinsert [" + users.size() + "] User success! " + key + "'s size is:" + userTemplate.opsForList().size(key));
-
}
-
-
public void leftpop(String key){
-
UserInfo userInfo = userTemplate.opsForList().leftPop(key, 2, TimeUnit.SECONDS);
-
//userTemplate.opsForList().leftPop(key);
-
AtomicInteger ai = new AtomicInteger(0);
-
while(userInfo != null){
-
ai.incrementAndGet();
-
userInfo = userTemplate.opsForList().leftPop(key, 2, TimeUnit.SECONDS);
-
}
-
log.info("pop [" + ai.get() + "] Users from " + key);
-
}
-
-
public void rightPopAndLeftPush(String srcKey){
-
String destinationKey = "destinationKey";
-
log.info("srcKey [" + srcKey + "]'s size : " + userTemplate.opsForList().size(srcKey));
-
log.info("destKey [" + destinationKey + "]'s size : " + userTemplate.opsForList().size(destinationKey));
-
UserInfo userInfo = userTemplate.opsForList().rightPopAndLeftPush(srcKey, destinationKey);
-
while(userInfo != null){
-
userInfo = userTemplate.opsForList().rightPopAndLeftPush(srcKey, destinationKey, 2, TimeUnit.SECONDS);
-
}
-
log.info("After rightPopAndLeftPush destKey [" + destinationKey + "]'s size : " + userTemplate.opsForList().size(destinationKey));
-
}
-
-
}
5.Set(集合)
-
public class SetTest extends RedisCommon {
-
-
public static void main(String[] args) throws InterruptedException {
-
log.info("-----------Starting Redis Set testing-----------");
-
ApplicationContext ctx = SpringApplication.run(SetTest.class, args);
-
StringRedisTemplate st = ctx.getBean(StringRedisTemplate.class);
-
String key = "SetKey";
-
String destKey = "DestKey";
-
String[] values = new String[]{"value1","value2","value3","value4","value5","value6","value7"};
-
log.info("SetKey add [" + st.opsForSet().add(key, values ) + "] values ");
-
log.info("SetKey's member " + st.opsForSet().members(key));
-
String value5 = "value5";
-
log.info(value5 + " is member of SetKey's : " + st.opsForSet().isMember(key, value5));
-
log.info("SetKey's randomMember [" + st.opsForSet().randomMember(key) + "]");
-
log.info("SetKey's size: " + st.opsForSet().size(key));
-
-
String[] subValues = new String[]{"value1","value2","value3"};
-
log.info("SetKey remove " + st.opsForSet().remove(key, subValues) + " members");
-
log.info("SetKey's size: " + st.opsForSet().size(key));
-
-
log.info("SetKey move to DestKey: " + st.opsForSet().move(key, value5, destKey));
-
log.info("SetKey's size: " + st.opsForSet().size(key));
-
log.info("DestKey size: " + st.opsForSet().size(destKey));
-
-
String popValue = st.opsForSet().pop(key);
-
log.info("SetKey move to DestKey: " + st.opsForSet().move(key, popValue, destKey));
-
log.info("SetKey's size: " + st.opsForSet().size(key));
-
log.info("DestKey size: " + st.opsForSet().size(destKey));
-
-
//st.opsForSet().difference(key, destKey);
-
//st.opsForSet().differenceAndStore(key, otherKeys, destKey);
-
-
//st.opsForSet().intersect(key, destKey);
-
//st.opsForSet().intersectAndStore(key, otherKey, destKey);
-
}
-
-
}
6.SortedSet(有序集合)
-
public class ZSetTest extends RedisCommon {
-
-
public static void main(String[] args) throws InterruptedException {
-
log.info("-----------Starting Redis ZSet testing-----------");
-
ApplicationContext ctx = SpringApplication.run(ZSetTest.class, args);
-
StringRedisTemplate st = ctx.getBean(StringRedisTemplate.class);
-
String key = "ZSetKey";
-
Set<TypedTuple<String>> values = new HashSet<>();
-
for (int i = 0; i < 10; i++) {
-
TypedTuple<String> tuple = new DefaultTypedTuple<String>("value-"
-
+ i, 12d + i);
-
values.add(tuple);
-
}
-
// log.info("SetKey add [" + st.opsForZSet().add(key, values) + "] values");
-
//st.opsForZSet().add(key, value, score)
-
//st.opsForZSet().incrementScore(key, value, delta)
-
log.info("SetKey has [" + st.opsForZSet().size(key) + "] values");
-
-
double start = 15d;
-
double end = 18d;
-
log.info("SetKey between " + start + " and " + end + " have " + st.opsForZSet().count(key, start, end));
-
-
long s = 1;
-
long e = 5;
-
log.info("SetKey range from " + s + " to " + e + " have " + st.opsForZSet().range(key, s, e));
-
//st.opsForZSet().rangeByScore(key, min, max, offset, count)
-
//st.opsForZSet().rangeByScoreWithScores(key, min, max)
-
//st.opsForZSet().rangeByScoreWithScores(key, min, max, offset, count)
-
//st.opsForZSet()
-
-
String member = "value-5";
-
log.info(member + "'s rank is " + st.opsForZSet().rank(key, member) + " in SetKey.");
-
-
log.info("Remove " + member + " from SetKey : " + st.opsForZSet().remove(key, member));
-
-
// st.opsForZSet().removeRange(key, start, end)
-
// st.opsForZSet().removeRangeByScore(key, min, max)
-
// st.opsForZSet().reverseRange(key, start, end)
-
// st.opsForZSet().reverseRangeByScore(key, min, max)
-
// st.opsForZSet().reverseRangeByScoreWithScores(key, min, max)
-
// st.opsForZSet().reverseRank(key, o)
-
// st.opsForZSet().unionAndStore(key, otherKeys, destKey)
-
// st.opsForZSet().unionAndStore(key, otherKey, destKey)
-
}
-
-
}
7.Pub/Sub(发布/订阅)
-
public class TopicTest extends RedisCommon {
-
private static String topicName = "Topic:chat";
-
-
-
RedisMessageListenerContainer container(
-
RedisConnectionFactory connectionFactory,
-
MessageListenerAdapter listenerAdapter) {
-
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
-
container.setConnectionFactory(connectionFactory);
-
container.addMessageListener(listenerAdapter, new PatternTopic(topicName));
-
//container.addMessageListener(listenerAdapter, new ChannelTopic(topicName));
-
return container;
-
}
-
-
-
MessageListenerAdapter listenerAdapter(Receiver receiver) {
-
return new MessageListenerAdapter(receiver, "receiveMessage");
-
}
-
-
-
Receiver receiver(@Value("Receiver-1") String name) {
-
return new Receiver(name);
-
}
-
-
public static void main(String[] args) throws InterruptedException {
-
log.info("-----------Starting Redis Topic testing-----------");
-
ApplicationContext ctx = SpringApplication.run(TopicTest.class, args);
-
StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
-
template.convertAndSend(topicName, "Hello from Redis!");
-
}
-
-
static class Receiver {
-
private String name;
-
-
-
public Receiver(String name) {
-
this.name = name;
-
}
-
-
public void receiveMessage(String message) {
-
log.info(name + " received <" + message + ">");
-
}
-
}
-
-
}
源码请戳这里。
梅花香自古寒来