Home Database Redis How to use Java to operate Redis database

How to use Java to operate Redis database

May 27, 2023 pm 05:52 PM
java redis database

Redis is a memory-based database that interacts with Redis to greatly improve the speed of operation.

First let us create a normal Maven project and add the corresponding dependencies

<dependencies>
		<dependency>
		    <groupId>redis.clients</groupId>
		    <artifactId>jedis</artifactId>
		    <version>3.3.0</version>
		</dependency>
		
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.72</version>
		</dependency>
  </dependencies>
Copy after login

Then we can use

to test the connection (here I use the local reids service)

//定义主机号、端口号
		HostAndPort hostAndPort = new HostAndPort("127.0.0.1",6379);
		//连接redis服务
		Jedis jedis=new Jedis(hostAndPort);
		//ping一下
		System.out.println("服务正在运行: "+jedis.ping())
		//关闭
		jedis.close();
Copy after login
控制台输出PONG代表连接成功
Copy after login

Next let’s look at the basic operations of Redis’s five major data types

  • String type

System.out.println("存入一个数据:"+jedis.set("age", "20"));
		System.out.println("存入多个数据:"+jedis.mset("name","zhangsan","sex","男"));
		
		System.out.println("获取一个数据:"+jedis.get("age"));
		System.out.println("获取多个数据:"+jedis.mget("name","sex"));
		
		System.out.println("将指定的字符串拼接在指定数据之后:"+jedis.append("name",",你好"));
		
		System.out.println("查看某个数据的长度:"+jedis.strlen("name"));
		
		System.out.println("修改某个数据的值并返回修改之前的值:"+jedis.getSet("name", "lisi"));
		
		System.out.println("判断某个数据是否存在:"+jedis.exists("name"));
		
		System.out.println("为某个数据设置失效时间(单位/s):"+jedis.expire("name", 20));
		
		System.out.println("查看某个数据的剩余生存时间(s):"+jedis.ttl("name"));
		
		System.out.println("删除一个或多个数据:"+jedis.del("name","sex"));
Copy after login

View print results

  • Set type

System.out.println("向集合添加一个或多个元素:"+jedis.sadd("key1", "v1","v2","v3"));
		
		System.out.println("获取集合的元素个数:"+jedis.scard("key1"));
		
		System.out.println("返回集合中的所有元素:"+jedis.smembers("key1"));
		
		System.out.println("判断指定元素是否存在集合中:"+jedis.sismember("key1", "v1"));
		
		System.out.println("移除集合中指定的元素:"+jedis.srem("key1", "v3"));
		
		//这里我们在创建一个集合
		System.out.println("向集合添加一个或多个元素:"+jedis.sadd("key2", "v2","v3","v4"));
		
		System.out.println("返回集合key1与key2的差集:"+jedis.sdiff("key1","key2"));
		System.out.println("返回集合key1与key2的交集:"+jedis.sinter("key1","key2"));
		System.out.println("返回集合key1与key2的并集:"+jedis.sunion("key1","key2"));
Copy after login

View results

  • Hash type

	Map map=new HashMap<>();
		map.put("name", "zhangsan");
		map.put("age", "20");
		map.put("sex", "男");
		
		System.out.println("创建一个哈希表存储一个用户对象:"+jedis.hmset("user",map));
		
		System.out.println("获取哈希表中用户的name:"+jedis.hget("user", "name"));
		
		System.out.println("查看哈希表中,指定的字段是否存在:"+jedis.hexists("user", "name"));
		
		System.out.println("获取哈希表中字段的数量:"+jedis.hlen("user"));
		
		System.out.println("获取哈希表中所有字段:"+jedis.hkeys("user"));
		
		System.out.println("获取哈希表中所有字段的值:"+jedis.hvals("user"));
		
		System.out.println("获取在哈希表中的所有字段和值:"+jedis.hgetAll("user"));
		
		System.out.println("删除一个或多个哈希表字段:"+jedis.hdel("user","name","age","sex"));
Copy after login

View results

  • List type

System.out.println("将一个值插入到列表头部(可以多个值):"+jedis.lpush("city","北京","上海"));
		
		
		System.out.println("将一个值插入到列表尾部(可以多个值):"+jedis.rpush("city","济南","南京"));
		
		
		System.out.println("获取列表指定范围内的元素:"+jedis.lrange("city", 0, -1));
		
		
		System.out.println("获取列表长度:"+jedis.llen("city"));
		
		
		System.out.println("移出列表的第一个元素,并输出值:"+jedis.lpop("city"));
		
		
		System.out.println("移除列表的最后一个元素,并输出值:"+jedis.rpop("city"));
		
		
		System.out.println("修改列表中指定索引位置元素的值:"+jedis.lset("city", 0, "西藏"));
		
		
		System.out.println("让列表只保留指定区间内的元素,不在指定区间之内的元素都将被删除:"+jedis.ltrim("city", 1, 2));
Copy after login

View results

  • Sorted Set type

Map<String,Double> scoreMembers=new HashMap<>();
		scoreMembers.put("member1", 1D);
		scoreMembers.put("member2", 2D);
		scoreMembers.put("member3", 3D);
		
		System.out.println("向有序集合添加一个或多个元素,或者更新已存在元素的分数:"+jedis.zadd("member", scoreMembers));
		
		System.out.println("获取有序集合的元素个数:"+jedis.zcard("member"));
		
		System.out.println("计算在有序集合中指定区间([socre1,socre2])分数的成员数:"+jedis.zcount("member", 0D, 3D));
		
		System.out.println("通过索引区间返回有序集合指定区间内的元素,从低到高:"+jedis.zrange("member", 0,-1));
		
		System.out.println("返回索引区间返回有序集合指定区间内的元素,从高到低:"+jedis.zrevrange("member", 0,-1));
		
		System.out.println("返回有序集中指定元素的分数值:"+jedis.zscore("member", "member1"));
		
		System.out.println("移除有序集合中的一个或多个元素:"+jedis.zrem("member", "member1","member2"));
		
		System.out.println("返回有序集合中指定元素的索引:"+jedis.zrank("member", "member3"));
Copy after login

View results

Finally we briefly look at how to operate the database

	System.out.println("清空当前数据库:"+jedis.flushDB());
		
		System.out.println("清空所有数据库:"+jedis.flushAll());
		
		System.out.println("查看当前数据库存储数据的多少:"+jedis.dbSize());
		
		Set<String> keys = jedis.keys("*");
		System.out.println("查看当前数据库存储所有键值:"+keys);
		
		System.out.println("选择某个数据库:"+jedis.select(0));
Copy after login

View results

In fact, Redis also has three special storage types

  • Geospatial                                                   

Mainly used to store geographical location information and operate on the stored information, based on Sorts Set ordered collection

  • HyperLogLog

is used for cardinality statistics

  • Bitmap

## records only two states by operating binary (0,1) Information

The above is the detailed content of How to use Java to operate Redis database. For more information, please follow other related articles on the PHP Chinese website!

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)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

See all articles