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 ...
随机推荐
- Hive 教程(三)-DDL基础
DDL,Hive Data Definition Language,数据定义语言: 通俗理解就是数据库与库表相关的操作,本文总结一下基本方法 hive 数据仓库配置 hive 数据仓库默认位置在 hd ...
- mybatis插入出现org.apache.ibatis.executor.ExecutorException: No setter found for the keyProperty 'xxx'异常的原因
确定有setter方法,问题其实是xml文件中,insert的主键的列名写错了,如下,一开始写成ComId <insert id="insertCom" parameterT ...
- leecode刷题(30)-- 二叉树的后序遍历
leecode刷题(30)-- 二叉树的后序遍历 二叉树的后序遍历 给定一个二叉树,返回它的 后序 遍历. 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [3,2,1] 思路 ...
- Box-shadow制作漂亮的外阴影输入框
背景:之前做项目中的一个移动端页面,关于在搜索框中输入信息查找对应的照片 改了几次ui图之后,最终的搜索框的设计图如下: 开始做页面的时候,就想到了用box-shadow 来实现外阴影边框.用bord ...
- 禁止缩放meta标签
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale= ...
- python中format所有用法
平时只用参数匹配,偶尔看到别人的format用法楞住没反应过来,遂记下 #通过位置 print '{0},{1}'.format('hehe',20) print '{},{}'.format('he ...
- subversion(SVN)服务配置及使用方法
1.安装 yum install httpd httpd-devel subversion mod_dav_svn mod_auth_mysql -y 2.查看版本 svnserve --vers ...
- MySQL之RPM安装说明及配置
1.查看当前系统是否安装过Linux rpm -qa | grep -i mysql 未安装无任何输出:安装会打印对应mysql的rpm安装包. 2.准备安装包: MySQL-client-5.5.4 ...
- Delphi 数组与记录类型
- Linux进程管理工具之ps
1.PS进程管理指令 ps -aux USER:用户名称 PID:进程号 %CPU:进程占用CPU的百分比 %MEM:进程占用物理内存的百分比 VSZ:进程占用的虚拟内存大小(单位:KB) RS ...