search
HomeDatabaseRedisWhat are the common API operations of redis?

//设置键值对
//set key value [EX seconds] [PX milliseconds] [NX|XX]
//获取值
//get key
//删除键
//del key
//清空数据库
//flushdb
//获取list值
//lrange key start stop
//map类型
//hget key field
//hgetall key
//sortedset类型
package hgs.redislearn;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.jedis.Jedis;
/**
 * 
 *  <p>Description:Redis </p> 
 * @author guangshihao
 * @date 2018年9月28日 
 *
 */
public class RedisMainTest {
	Jedis jedis = null;
	@Before
	public void getConnect() {
		 jedis = new Jedis("192.168.6.129", 6379);
	}
	@Test
	public void sysoutConnect() {
		System.out.println(jedis.ping());
	}
	
	@After
	public void finaly() {
		jedis.close();
	}
	
	//测试放入String类型的键值对,并进行获取删除修改等操作
	@Test
	public void TestStringKeys() {
		jedis.set("hgs.name", "haoguangshi.");
		String name = jedis.get("hgs.name");
		System.out.println(name);
		long affect = jedis.del("hgs.name");
		System.out.println(affect);
	}
	
	@Test
	public void TestListKeys() {
		//从左边插入
		jedis.lpush("test_list", "1","2","100");
		//从右边插入
		jedis.rpush("test_list", "100","2","1","this");
		//获取list
		List<string>  lis = jedis.lrange("test_list", 0, -1);
		System.out.println(lis);
		//jedis.lpop lpush  rpop rpush
		//在this出现的第一个位置的前面插入is
		jedis.linsert("test_list", LIST_POSITION.BEFORE, "this", "is");
		
	}
	
	//map类型操作
	@Test
	public void TestMapKeys() throws JsonGenerationException, JsonMappingException, IOException {
/*		Person p = new Person ();
		p.setName("hgs");
		p.setAge(26);
		p.setWeight(65);
		
		
		Person p1 = new Person ();
		p1.setName("wd");
		p1.setAge(23);
		p1.setWeight(60);
		
		ObjectMapper mapper = new ObjectMapper();
		String sp = mapper.writer().writeValueAsString(p);
		String sp1 = mapper.writer().writeValueAsString(p1);
		
		Map<string> ps = new HashMap<string>();
		ps.put("hgs", sp);
		ps.put("wd", sp1);*/
		jedis.hset("pseron:hgs", "name", "hgs");
		jedis.hset("pseron:hgs", "age", "24");
		jedis.hset("pseron:hgs", "weigth", "65kg");
		
		jedis.hset("pseron:wd", "name", "wd");
		jedis.hset("pseron:wd", "age", "24");		
		jedis.hset("pseron:wd", "weight", "60kg");
		
	}
	@Test
	public void loopMapKeys() {
		//遍历一个map
		Map<string> wd = jedis.hgetAll("pseron:wd");
		for(String type : wd.keySet()) {
			System.out.println(type+" : " +wd.get(type));
		}
		//原子操作自增2
		jedis.hincrBy("pseron:hgs\"", "age", 2L);
	}
	
	@Test
	public void delMapKeys() {
		//删除属性
		jedis.hdel("pseron:wd", "weight");
		//打印集合的长度
		System.out.println(jedis.hlen("pseron:hgs"));
	}
	
	//set类型数据结构,添加数据
	@Test
	public void setKeysTest() {
		String[] tmp = new String[] {
			"tianmao","dingding","alimama","zhifubao","feizhu"	
		};
		jedis.sadd("apps", tmp);
		
		String[] tmp1 = new String[] {
				"tianmao","dingdi","alima","zhifubao","feizhu"	
			};
			jedis.sadd("apps", tmp);
			jedis.sadd("apps1", tmp1);
	}
	//遍历
	@Test 
	public void scanSetKeys() {
		//判断某个记录是否存在
		System.out.println(jedis.sismember("apps", "tianmao"));
		System.out.println(jedis.scard("apps"));
		//计算交集
		Set<string> sets = jedis.sinter("apps","apps1");
		for(String s : sets) {
			System.out.println(s);
		}
		
		//并集
		Set<string> sets1 = jedis.sunion("apps","apps1");
		for(String s : sets1) {
			System.out.println(s);
		}
		System.out.println();
		//差集
		Set<string> sets2 = jedis.sdiff("apps","apps1");
		for(String s : sets2) {
			System.out.println(s);
		}
		//遍历
		Set<string> sets3 = jedis.smembers("apps");
		for(String s : sets3) {
			System.out.println(s);
		}
	}
	//SortedSet数据类型
	//存数据
	@Test
	public void sortedSetAddTest() {
		Map<string> scoremem = new HashMap<string>();
		scoremem.put("wd", (double) 88);
		scoremem.put("cm", (double) 87);
		scoremem.put("zz", (double) 90);
		scoremem.put("wzf", (double) 70);
		scoremem.put("xzh", (double) 66);		
		scoremem.put("hgs", (double) 55);
		scoremem.put("hjh", (double) 88);
		scoremem.put("shk", (double) 100);		
		jedis.zadd("roommeets_score", scoremem);
	}
	//sortedSet 遍历
	@Test
	public void scanSortedSet() {
		//正序遍历
		Set<string>  members = jedis.zrange("roommeets_score", 0, -1);
		for(String mem : members) {
			System.out.println("name:"+mem +","+" score:" +jedis.zscore("roommeets_score", mem)+","+" rank:"+(jedis.zrank("roommeets_score", mem)+1));
		}
		System.out.println();
		//正序遍历
		Set<string>  members1 = jedis.zrevrange("roommeets_score", 0, -1);
		for(String mem : members1) {
			System.out.println("name:"+mem +","+" score:" +jedis.zscore("roommeets_score", mem)+","+" rank:"+(jedis.zrevrank("roommeets_score", mem)+1L));
		}
	}
}
class Person{
	String name ;
	int age;
	double weight;
	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;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", weight=" + weight + "]";
	}
	
	
	
}</string></string></string></string></string></string></string></string></string></string></string></string>

The above is the detailed content of What are the common API operations of redis?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Redis: The Advantages of a NoSQL ApproachRedis: The Advantages of a NoSQL ApproachApr 27, 2025 am 12:09 AM

Redis is a NoSQL database that provides high performance and flexibility. 1) Store data through key-value pairs, suitable for processing large-scale data and high concurrency. 2) Memory storage and single-threaded models ensure fast read and write and atomicity. 3) Use RDB and AOF mechanisms to persist data, supporting high availability and scale-out.

Redis: Understanding Its Architecture and PurposeRedis: Understanding Its Architecture and PurposeApr 26, 2025 am 12:11 AM

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

Redis vs. SQL Databases: Key DifferencesRedis vs. SQL Databases: Key DifferencesApr 25, 2025 am 12:02 AM

The main difference between Redis and SQL databases is that Redis is an in-memory database, suitable for high performance and flexibility requirements; SQL database is a relational database, suitable for complex queries and data consistency requirements. Specifically, 1) Redis provides high-speed data access and caching services, supports multiple data types, suitable for caching and real-time data processing; 2) SQL database manages data through a table structure, supports complex queries and transaction processing, and is suitable for scenarios such as e-commerce and financial systems that require data consistency.

Redis: How It Acts as a Data Store and ServiceRedis: How It Acts as a Data Store and ServiceApr 24, 2025 am 12:08 AM

Redisactsasbothadatastoreandaservice.1)Asadatastore,itusesin-memorystorageforfastoperations,supportingvariousdatastructureslikekey-valuepairsandsortedsets.2)Asaservice,itprovidesfunctionalitieslikepub/submessagingandLuascriptingforcomplexoperationsan

Redis vs. Other Databases: A Comparative AnalysisRedis vs. Other Databases: A Comparative AnalysisApr 23, 2025 am 12:16 AM

Compared with other databases, Redis has the following unique advantages: 1) extremely fast speed, and read and write operations are usually at the microsecond level; 2) supports rich data structures and operations; 3) flexible usage scenarios such as caches, counters and publish subscriptions. When choosing Redis or other databases, it depends on the specific needs and scenarios. Redis performs well in high-performance and low-latency applications.

Redis's Role: Exploring the Data Storage and Management CapabilitiesRedis's Role: Exploring the Data Storage and Management CapabilitiesApr 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.

Redis: Understanding NoSQL ConceptsRedis: Understanding NoSQL ConceptsApr 21, 2025 am 12:04 AM

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

Redis: Real-World Use Cases and ExamplesRedis: Real-World Use Cases and ExamplesApr 20, 2025 am 12:06 AM

The applications of Redis in the real world include: 1. As a cache system, accelerate database query, 2. To store the session data of web applications, 3. To implement real-time rankings, 4. To simplify message delivery as a message queue. Redis's versatility and high performance make it shine in these scenarios.

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.