Home Database Mysql Tutorial Java使用Redis初探

Java使用Redis初探

Jun 07, 2016 pm 04:10 PM
java redis No use Preliminary exploration concept Related

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
Copy after login


客户端使用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();
	}
}
Copy after login

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("连接已关闭.....");
//	}
	
}
Copy after login


这时候可以看到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
Copy after login

哎,先到这吧。。。。




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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
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...

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.

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...

Why is the return value empty when using RedisTemplate for batch query? Why is the return value empty when using RedisTemplate for batch query? Apr 19, 2025 pm 10:15 PM

Why is the return value empty when using RedisTemplate for batch query? When using RedisTemplate for batch query operations, you may encounter the returned results...

Redis: Understanding Its Architecture and Purpose Redis: Understanding Its Architecture and Purpose Apr 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.

Why does the redisTemplate.opsForList().leftPop() method not support passing in parameters to pop up multiple values ​​at once? Why does the redisTemplate.opsForList().leftPop() method not support passing in parameters to pop up multiple values ​​at once? Apr 19, 2025 pm 10:27 PM

Regarding the reason why RedisTemplate.opsForList().leftPop() does not support passing numbers. When using Redis, many developers will encounter a problem: Why redisTempl...

In a multi-node environment, how to ensure that Spring Boot's @Scheduled timing task is executed only on one node? In a multi-node environment, how to ensure that Spring Boot's @Scheduled timing task is executed only on one node? Apr 19, 2025 pm 10:57 PM

The optimization solution for SpringBoot timing tasks in a multi-node environment is developing Spring...

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

See all articles