Home Database Mysql Tutorial 【redis,1】java操作redis:将string、list、map、自定义的对象

【redis,1】java操作redis:将string、list、map、自定义的对象

Jun 07, 2016 pm 04:02 PM
java list map redis string operate

一、操作string 、list 、map 对象1、引入jar:jedis-2.1.0.jar 2、代码/** * @param args */ public static void main(String[] args) { //连接redis服务 Jedis jedis = new Jedis(192.168.88.15,6379); //密码验证-如果你没有设置redis密码可不验证即可使用

一、操作string 、list 、map 对象 1、引入jar: jedis-2.1.0.jar 2、代码 /** * @param args */ public static void main(String[] args) { //连接redis服务 Jedis jedis = new Jedis("192.168.88.15",6379); //密码验证-如果你没有设置redis密码可不验证即可使用相关命令 // jedis.auth("abcdefg"); //简单的key-value 存储 jedis.set("redis", "myredis"); System.out.println(jedis.get("redis")); //在原有值得基础上添加,如若之前没有该key,则导入该key //之前已经设定了redis对应"myredis",此句执行便会使redis对应"myredisyourredis" jedis.append("redis", "yourredis"); jedis.append("content", "rabbit"); //mset 是设置多个key-value值 参数(key1,value1,key2,value2,...,keyn,valuen) //mget 是获取多个key所对应的value值 参数(key1,key2,key3,...,keyn) 返回的是个list jedis.mset("name1","yangw","name2","demon","name3","elena"); System.out.println(jedis.mget("name1","name2","name3")); //map Map user = new HashMap(); user.put("name", "cd"); user.put("password", "123456"); //map存入redis jedis.hmset("user", user); //mapkey个数 System.out.println(String.format("len:%d", jedis.hlen("user"))); //map中的所有键值 System.out.println(String.format("keys: %s", jedis.hkeys("user") )); //map中的所有value System.out.println(String.format("values: %s", jedis.hvals("user") )); //取出map中的name字段值 List rsmap = jedis.hmget("user", "name","password"); System.out.println(rsmap); //删除map中的某一个键值 password jedis.hdel("user", "password"); System.out.println(jedis.hmget("user", "name", "password")); //list jedis.del("listDemo"); System.out.println(jedis.lrange("listDemo", 0, -1)); jedis.lpush("listDemo", "A"); jedis.lpush("listDemo", "B"); jedis.lpush("listDemo", "C"); System.out.println(jedis.lrange("listDemo", 0, -1)); System.out.println(jedis.lrange("listDemo", 0, 1)); //set jedis.sadd("sname", "wobby"); jedis.sadd("sname", "kings"); jedis.sadd("sname", "demon"); System.out.println(String.format("set num: %d", jedis.scard("sname"))); System.out.println(String.format("all members: %s", jedis.smembers("sname"))); System.out.println(String.format("is member: %B", jedis.sismember("sname", "wobby"))); System.out.println(String.format("rand member: %s", jedis.srandmember("sname"))); //删除一个对象 jedis.srem("sname", "demon"); System.out.println(String.format("all members: %s", jedis.smembers("sname"))); } 二、将自定义对象保存到redis中:
1、自定义pojo 实现Serializable 接口: package cn.mingyuan.redis; import java.io.Serializable; /** * 测试用pojo,实现了Serializable,以便进行系列化操作 * * @author mingyuan * */ public class Person implements Serializable { private static final long serialVersionUID = -3562550857760039655L; private String name; private int age; public Person(){} public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } } 2、测试类: package cn.mingyuan.redis; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import redis.clients.jedis.Jedis; public class Test { /** * @param args * @throws IOException * @throws ClassNotFoundException */ public static void main(String[] args) throws IOException, ClassNotFoundException { // Jedis redis = new Jedis("192.168.88.15"); Jedis redis = new Jedis("192.168.88.15", 6379); // connect可以不要,因为在执行set操作的时候会先进行判断客户端是否于服务器端建立了连接,若无,则启动连接过程 redis.connect(); String set = redis.set("mingyuan", "1"); System.out.println(" set result \t" + set); redis.incr("mingyuan"); String string = redis.get("mingyuan"); System.out.println(" get result of key 'mingyuan' \t" + string); // 下面是对对象进行存储的测试代码 ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); Person person = new Person("liudehua" ,22); oos.writeObject(person); byte[] byteArray = bos.toByteArray(); oos.close(); bos.close(); String setObjectRet = redis.set("mingyuan".getBytes(), byteArray); System.out.println(" set object return \t" + setObjectRet); byte[] bs = redis.get("mingyuan".getBytes()); ByteArrayInputStream bis = new ByteArrayInputStream(bs); ObjectInputStream inputStream = new ObjectInputStream(bis); Person readObject = (Person) inputStream.readObject(); System.out.println(" read object \t" + readObject.toString()); inputStream.close(); bis.close(); redis.disconnect(); } }
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to configure slow query log in centos redis How to configure slow query log in centos redis Apr 14, 2025 pm 04:54 PM

Enable Redis slow query logs on CentOS system to improve performance diagnostic efficiency. The following steps will guide you through the configuration: Step 1: Locate and edit the Redis configuration file First, find the Redis configuration file, usually located in /etc/redis/redis.conf. Open the configuration file with the following command: sudovi/etc/redis/redis.conf Step 2: Adjust the slow query log parameters in the configuration file, find and modify the following parameters: #slow query threshold (ms)slowlog-log-slower-than10000#Maximum number of entries for slow query log slowlog-max-len

How to install redis in centos7 How to install redis in centos7 Apr 14, 2025 pm 08:21 PM

What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot? What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot? Apr 19, 2025 pm 08:03 PM

In SpringBoot, use Redis to cache OAuth2Authorization object. In SpringBoot application, use SpringSecurityOAuth2AuthorizationServer...

Redis's Role: Exploring the Data Storage and Management Capabilities Redis's Role: Exploring the Data Storage and Management Capabilities Apr 22, 2025 am 12:10 AM

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

Laravel8 optimization points Laravel8 optimization points Apr 18, 2025 pm 12:24 PM

Laravel 8 provides the following options for performance optimization: Cache configuration: Use Redis to cache drivers, cache facades, cache views, and page snippets. Database optimization: establish indexing, use query scope, and use Eloquent relationships. JavaScript and CSS optimization: Use version control, merge and shrink assets, use CDN. Code optimization: Use Composer installation package, use Laravel helper functions, and follow PSR standards. Monitoring and analysis: Use Laravel Scout, use Telescope, monitor application metrics.

See all articles