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";
- @Bean
- 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;
- }
- @Bean
- MessageListenerAdapter listenerAdapter(Receiver receiver) {
- return new MessageListenerAdapter(receiver, "receiveMessage");
- }
- @Bean
- 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;
- @Autowired
- public Receiver(String name) {
- this.name = name;
- }
- public void receiveMessage(String message) {
- log.info(name + " received <" + message + ">");
- }
- }
- }
源码请戳这里。
Java操作Redis数据的更多相关文章
- java 操作redis
使用Java操作Redis需要jedis-2.1.0.jar,如果需要使用Redis连接池的话,还需commons-pool-1.5.4.jar package com.test; import ja ...
- windows下Redis安装及利用java操作Redis
一.windows下Redis安装 1.Redis下载 下载地址:https://github.com/MicrosoftArchive/redis 打开下载地址后,选择版本 然后选择压缩包 下载 R ...
- java操作redis集群配置[可配置密码]和工具类
java操作redis集群配置[可配置密码]和工具类 <dependency> <groupId>redis.clients</groupId> & ...
- Linux+Redis实战教程_day02_3、redis数据类型_4、String命令_5、hash命令_6、java操作redis数据库技术
3. redis数据类型[重点] redis 使用的是键值对保存数据.(map) key:全部都是字符串 value:有五种数据类型 Key名:自定义,key名不要过长,否则影响使用效率 Key名不要 ...
- java操作redis学习(一):安装及连接
文章参考自:http://www.cnblogs.com/edisonfeng/p/3571870.html,在此基础上进行了修改. 一.下载安装Redis redis官网显示暂时不支持Windows ...
- Java操作redis【二十】
1.首先需要将redis的绑定地址为127.0.0.1去掉,同时将redis的保护模式去掉,并且开放6379端口. 如果是保护模式需要输入密码才能连接. (1)去掉绑定地址: (2)去掉保护模式: ( ...
- 使用Java操作Redis(一)
Redis是一款基于key-value的数据库服务器,安装完成后我们可以通过redis-cli使用Redis提供的命令完成各种操作.redis-cli实际上就是一款客户端,和redis-server建 ...
- Redis基础知识、命令以及java操作Redis
1 nosql的概念 sql:操作(关系型)数据库的标准查询语言 关系型数据库(rdbms):以关系(由行和列组成的二维表)模型为核心数据库,有表的储存系统.(mysql.oracle.sqlserv ...
- 最全的Java操作Redis的工具类,使用StringRedisTemplate实现,封装了对Redis五种基本类型的各种操作!
转载自:https://github.com/whvcse/RedisUtil 代码 ProtoStuffSerializerUtil.java import java.io.ByteArrayInp ...
随机推荐
- MySQL的库、表的详细操作
目录 MySQL的库.表的详细操作 一 库操作 二 表操作 MySQL的库.表的详细操作 本节目录 一 库操作 1.创建数据库 1.1 语法 CREATE DATABASE 数据库名 charset ...
- windows 安装 python 踩坑记录
官方不建议使用 64 bit python,容易出各种问题 Unable to find vcvarsall.bat 凡是安装与操作系统底层相关的 python 扩展都会遇到这个问题,如 PIL,Pi ...
- JS中this的4种绑定规则
this ES6中的箭头函数采用的是词法作用域. 为什么要使用this:使API设计得更简洁且易于复用. this即不指向自身,也不指向函数的词法作用域. this的指向只取决于函数的调用方式 thi ...
- jsp页面中使用 splitfn:split注意事项
我们有一个 字段存储内容是 xxxx意见~~@~~是 在页面上需要分开显示,格式为 xxx意见 是 使用 ${fn:split(comments, '~~@~~')[1]} 来分割是发现出现@符文字 ...
- @babel/traverse 使用方法小记
@babel/traverse 官网: https://babeljs.io/docs/en/babel-traverse github:https://github.com/babel/babel/ ...
- js 格式化 json 字符串
1.JSON.stringify的三个参数 var json = {"@odata.context":"$metadata#AddTableOne_466281s&quo ...
- Redhat 7修改主机名
修改主机名: Linux master2 3.10.0-693.el7.x86_64 #1 SMP Thu Jul 6 19:56:57 EDT 2017 x86_64 x86_64 x86_64 G ...
- String,到底创建了多少个对象?
String str=new String("aaa"); <span style="font-size:14px;">String str=n ...
- 第十篇.1、python并发编程之多进程理论部分
一 什么是进程 进程:正在进行的一个过程或者说一个任务.而负责执行任务则是cpu. 举例(单核+多道,实现多个进程的并发执行): egon在一个时间段内有很多任务要做:python备课的任务,写书的任 ...
- linux上安装rz和sz
简介 lrzsz 官网入口:http://freecode.com/projects/lrzsz/ lrzsz是一个unix通信套件提供的X,Y,和ZModem文件传输协议 windows 需要向ce ...