search
HomeDatabaseMysql TutorialJava使用Redis初探

Java使用Redis初探

Jun 07, 2016 pm 04:10 PM
javaredisNousePreliminary explorationconceptRelated

Redis的相关概念不做介绍了,大家也可以先了解下Memcached,然后比较下二者的区别,就会有个整体的印象。 服务器端通常选择Linux , Redis对于linux是官方支持的,使用资料很多,需要下载相关服务器端程序 ,然后解压安装。因为能力和条件有限,我只简单介绍下

Redis的相关概念不做介绍了,大家也可以先了解下Memcached,然后比较下二者的区别,就会有个整体的印象。

服务器端通常选择Linux , Redis对于linux是官方支持的,使用资料很多,需要下载相关服务器端程序 ,然后解压安装。因为能力和条件有限,我只简单介绍下windows上如何安装和使用,有兴趣的可以娱乐一下。

服务器端程序下载地址:https://github.com/ServiceStack/redis-windows.git

如果不好操作的话到这来:http://download.csdn.net/detail/u013283727/8212831

下载完后使用cmd进入下载文件的目录中,尝试以下操作:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\>cd redis64-latest

C:\redis64-latest>redis-server redis.windows.conf --maxmemory 200m
                _._
           _.-``__ ''-._
      _.-``    `.  `_.  ''-._           Redis 2.8.17 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._
 (    '      ,       .-`  | `,    )     Running in stand alone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 4552
  `-._    `-._  `-./  _.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |           http://redis.io
  `-._    `-._`-.__.-'_.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |
  `-._    `-._`-.__.-'_.-'    _.-'
      `-._    `-.__.-'    _.-'
          `-._        _.-'
              `-.__.-'

[4552] 01 Dec 13:38:53.147 # Server started, Redis version 2.8.17
[4552] 01 Dec 13:38:53.147 * DB loaded from disk: 0.000 seconds
[4552] 01 Dec 13:38:53.147 * The server is now ready to accept connections on po
rt 6379


客户端使用java程序来连接,在这里介绍两种常用的方法

(Jar包直接找maven要:http://www.mvnrepository.com 一搜就出来了)

1.Redisson

/**
 * @author fcs
 * Redisson Example
 */
public class RedissonTest {
	public static void main(String[] args) {
		//1.初始化
		Config config = new Config();
		config.setConnectionPoolSize(10);
		config.addAddress("127.0.0.1:6379");
		Redisson redisson = Redisson.create(config);
		System.out.println("redis连接接成功。。。。。");
		
		//2.测试concurrentMap,put时候就会同步到redis中
		ConcurrentMap<String, String> map = redisson.getMap("firstMap");
		map.put("changshengfeng", "男");
		map.put("yongtaoliu", "男");
		map.put("qiaozhu", "女");
		
		ConcurrentMap resultMap = redisson.getMap("firstMap");
		System.out.println("resultMap == "+resultMap.keySet());
		//关闭连接
		redisson.shutdown();
	}
}

2.Jedis

/**
 * @author fcs
 * test about jedis
 * Dec 1, 2014
 */
public class JedisTest {
	private static Jedis jedis;
	
	@Before
	public void setup(){
		jedis = new Jedis("127.0.0.1", 6379);
		System.out.println("Redis服务器已连接....");
//		jedis.auth("admin");   //权限验证
	}
	
	/**
	 * redis 存储字符串
	 */
	@Test
	public void testString(){
		//添加数据
		jedis.set("name", "fcs");
		System.out.println(jedis.get("name"));//获取结果
		
		jedis.append("name", "is handsome");//拼接
		
		jedis.del("name");//删除某个键
		System.out.println(jedis.get("name"));
		
		jedis.mset("name","changsheng","age","22","qq","646653132");//设置多个键值对
		jedis.incr("age");//加1操作   在投票中可能用的上
		System.out.println(jedis.get("name")+"--"+jedis.get("age")+"--"+jedis.get("qq"));
	}
	
	/**
	 * 操作List
	 */
	@Test
	public void testList(){
		jedis.del("java framework");
		System.out.println(jedis.lrange("java framework", 0, -1));
		//先向key java framework存放三条数据
		jedis.lpush("java framework", "spring");
		jedis.lpush("java framework", "struts");
		jedis.lpush("java framework", "hibernate");
		//再取出所有数据jedis.lrange是按范围取出  第一个是key  第二个是其实位置  第三个是结束位置
		System.out.println(jedis.lrange("java framework", 0, -1));
		
		jedis.del("java framework");
		jedis.rpush("java framework", "spring");
		jedis.rpush("java framework", "struts");
		jedis.rpush("java framework", "hibernate");
		//再取出所有数据jedis.lrange是按范围取出  第一个是key  第二个是其实位置  第三个是结束位置
		System.out.println(jedis.lrange("java framework", 0, -1));
		
	}
	
	/**
	 * 操作Set
	 */
	@Test
	public void testSet(){
		jedis.sadd("haha", "why");
		jedis.sadd("haha", "you");
		jedis.sadd("haha", "so");
		jedis.sadd("haha", "diao");
		jedis.sadd("haha", "?");
		//移除
		jedis.srem("haha", "?");
		System.out.println("判断?是不是haha集合的元素:"+jedis.sismember("haha", "?"));
		System.out.println("获取所有加入的value:"+jedis.smembers("haha"));
		System.out.println("返回给定集合名的一个随机的value:"+jedis.srandmember("haha"));
		System.out.println("返回集合的元素个数:"+jedis.scard("haha"));
		
	}
	
	/**
	 * redis 操作map
	 */
	@Test
	public void testmap(){
		Map<String,String> map = new HashMap<String, String>();
		map.put("name", "小露");
		map.put("sex", "男");
		map.put("email", "haha@fcs.com");
		jedis.hmset("user", map);//相当于给map再取一个名字
		
		List<String> rsmap = jedis.hmget("user", "name","sex");//后面是一个可变参数列表  去某个map中的一些key代表的值
		System.out.println(rsmap);
		
		//删除map中的某个键值
		jedis.hdel("user", "email");
		System.out.println("删除后----email"+jedis.hmget("user", "email"));
		System.out.println("是否存在key为user的记录:"+jedis.exists("user"));
		System.out.println("key为user的map中存放的值的个数:"+jedis.hlen("user"));
		System.out.println("返回map对象中所有的key:"+jedis.hkeys("user"));
		System.out.println("返回map对象中所有的value:"+jedis.hvals("user"));
		
		//使用迭代器
		Iterator<String> iter = jedis.hkeys("user").iterator();
		System.out.println("***************使用迭代器***************");
		while(iter.hasNext()){
			String key = iter.next();//每次向后越过一个对象
			System.out.println(key+":"+jedis.hmget("user", key));//迭代key   根据key再取值value
		}

	}
	
	/**
	 * 这里在前面执行完之后直接再去拿值   试试这些进驻内存的数据是否还在
	 * 可以把服务器端关掉再重启    再直接运行这个方法看看
	 * 如果还有数据就说明该数据库自动完成了持久化     它有默认的持久化机制
	 */
	@Test
	public void testNoSet(){
		Iterator<String> iter = jedis.hkeys("user").iterator();
		System.out.println("***************使用迭代器***************");
		while(iter.hasNext()){
			String key = iter.next();//每次向后越过一个对象
			System.out.println(key+":"+jedis.hmget("user", key));//迭代key   根据key再取值value
		}
	}

//	@AfterClass   测试整个类时可以用    会关闭服务器端程序
//	public static void close(){
//		jedis.shutdown();//不能用@After   不然每次执行完一个方法都会关闭服务器
//		System.out.println("连接已关闭.....");
//	}
	
}


这时候可以看到cmd中有一些日志记录:(这就是它默认的持久化机制,可以在redis.windows.conf配置文件中查看)

[3972] 01 Dec 13:59:04.073 * 1 changes in 900 seconds. Saving...
[3972] 01 Dec 13:59:04.229 # fork operation complete
[3972] 01 Dec 13:59:04.229 * Background saving terminated with success
[3972] 01 Dec 14:20:05.127 * 1 changes in 900 seconds. Saving...
[3972] 01 Dec 14:20:05.267 # fork operation complete
[3972] 01 Dec 14:20:05.267 * Background saving terminated with success
[3972] 01 Dec 14:35:06.074 * 1 changes in 900 seconds. Saving...
[3972] 01 Dec 14:35:06.204 # fork operation complete
[3972] 01 Dec 14:35:06.224 * Background saving terminated with success

哎,先到这吧。。。。




Statement
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
MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQL: String Data Types and ENUMs?MySQL: String Data Types and ENUMs?May 13, 2025 am 12:05 AM

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

MySQL BLOB: how to optimize BLOBs requestsMySQL BLOB: how to optimize BLOBs requestsMay 13, 2025 am 12:03 AM

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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.