A preliminary study of using Redis in Java

Source: Internet
Author: User
Tags redis version redis server



Redis related concepts Do not introduce, we can first understand the next memcached, and then compare the difference between the two, there will be a whole impression.






Server side usually choose Linux, Redis for Linux is officially supported, use a lot of data, need to download the relevant server-side programs, and then unzip the installation. Because of the limited capacity and conditions, I will simply describe how to install and use Windows, interested in entertainment.



Server-side program: Https://github.com/ServiceStack/redis-windows.git


If it's not working, come here: http://download.csdn.net/detail/u013283727/8212831


After downloading, use CMD to enter the directory where you downloaded the file, try the following:

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

C: \ Users \ WH141006P> cd
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


The client uses a java program to connect, here introduces two commonly used methods

(Jar package can be found directly from maven: http://www.mvnrepository.com and it will come out after a search)

1. Redisson

/ **
 * @author fcs
 * Redisson Example
 * /
public class RedissonTest {
public static void main (String [] args) {
// 1. Initialization
Config config = new Config ();
config.setConnectionPoolSize (10);
config.addAddress ("127.0.0.1:6379");
Redisson redisson = Redisson.create (config);
System.out.println ("redis connected successfully ...");
The
// 2. Test concurrentMap, it will be synchronized to redis when put
ConcurrentMap <String, String> map = redisson.getMap ("firstMap");
map.put ("changshengfeng", "Male");
map.put ("yongtaoliu", "Male");
map.put ("qiaozhu", "Female");
The
ConcurrentMap resultMap = redisson.getMap ("firstMap");
System.out.println ("resultMap ==" + resultMap.keySet ());
// Close the connection
redisson.shutdown ();
}
}

2.Jedis
/ **
 * @author WH141006P
 * test about jedis
 * Dec 1, 2014
 * /
public class JedisTest {
private static Jedis jedis;
The
@Before
public void setup () {
jedis = new Jedis ("127.0.0.1", 6379);
System.out.println ("Redis server is connected ...");
// jedis.auth ("admin"); // Authentication
}
The
/ **
* redis storage string
* /
@Test
public void testString () {
//adding data
jedis.set ("name", "fcs");
System.out.println (jedis.get ("name")); // Get the result
The
jedis.append ("name", "is handsome"); // Stitching
The
jedis.del ("name"); // Delete a key
System.out.println (jedis.get ("name"));
The
jedis.mset ("name", "changsheng", "age", "22", "qq", "646653132"); // Set multiple key-value pairs
jedis.incr ("age"); // Add 1 operation may be used in voting
System.out.println (jedis.get ("name") + "-" + jedis.get ("age") + "-" + jedis.get ("qq"));
}
The
/ **
* Operation List
* /
@Test
public void testList () {
jedis.del ("java framework");
System.out.println (jedis.lrange ("java framework", 0, -1));
// First store three data to the key java framework
jedis.lpush ("java framework", "spring");
jedis.lpush ("java framework", "struts");
jedis.lpush ("java framework", "hibernate");
// Retrieve all the data jedis.lrange is retrieved according to the range. The first is the key. The second is the actual position. The third is the end position.
System.out.println (jedis.lrange ("java framework", 0, -1));
The
jedis.del ("java framework");
jedis.rpush ("java framework", "spring");
jedis.rpush ("java framework", "struts");
jedis.rpush ("java framework", "hibernate");
// Retrieve all the data jedis.lrange is retrieved according to the range. The first is the key. The second is the actual position. The third is the end position.
System.out.println (jedis.lrange ("java framework", 0, -1));
The
}
The
/ **
* Operation Set
* /
@Test
public void testSet () {
jedis.sadd ("haha", "why");
jedis.sadd ("haha", "you");
jedis.sadd ("haha", "so");
jedis.sadd ("haha", "diao");
jedis.sadd ("haha", "?");
// remove
jedis.srem ("haha", "?");
System.out.println ("Judgment? Is it an element of haha collection:" + jedis.sismember ("haha", "?"));
System.out.println ("Get all added values:" + jedis.smembers ("haha"));
System.out.println ("Return a random value for the given set name:" + jedis.srandmember ("haha"));
System.out.println ("Return the number of elements in the collection:" + jedis.scard ("haha"));
The
}
The
/ **
* redis operation map
* /
@Test
public void testmap () {
Map <String, String> map = new HashMap <String, String> ();
map.put ("name", "小 露");
map.put ("sex", "Male");
map.put ("email", "[email protected]");
jedis.hmset ("user", map); // It is equivalent to giving the map another name
The
List <String> rsmap = jedis.hmget ("user", "name", "sex"); // Followed by a variable parameter list, go to the value represented by some key in a map
System.out.println (rsmap);
The
// Delete a key value in the map
jedis.hdel ("user", "email");
System.out.println ("After deletion ---- email" + jedis.hmget ("user", "email"));
System.out.println ("Whether there is a record with key as user:" + jedis.exists ("user"));
System.out.println ("key is the number of values stored in the user's map:" + jedis.hlen ("user"));
System.out.println ("Return all keys in the map object:" + jedis.hkeys ("user"));
System.out.println ("Return all values in the map object:" + jedis.hvals ("user"));
The
// Use iterator
Iterator <String> iter = jedis.hkeys ("user"). Iterator ();
System.out.println ("*************** Use iterator ***************");
while (iter.hasNext ()) {
String key = iter.next (); // Cross back one object at a time
System.out.println (key + ":" + jedis.hmget ("user", key)); // Iterate the key and then take the value according to the key
}

}
The
/ **
* Here, go directly to get the value after the previous execution. Try whether the data in the memory is still there
* You can turn off and restart the server, then run this method directly
* If there is data, it means that the database has automatically completed persistence. It has a default persistence mechanism
* /
@Test
public void testNoSet () {
Iterator <String> iter = jedis.hkeys ("user"). Iterator ();
System.out.println ("*************** Use iterator ***************");
while (iter.hasNext ()) {
String key = iter.next (); // Cross back one object at a time
System.out.println (key + ":" + jedis.hmget ("user", key)); // Iterate the key and then take the value according to the key
}
}

// @AfterClass can be used when testing the entire class, it will close the server-side program
// public static void close () {
// jedis.shutdown (); // You can't use @After or the server will be shut down every time a method is executed
// System.out.println ("The connection is closed ...");
//}
The
}


At this time, you can see that there are some log records in cmd: (This is its default persistence mechanism, which can be viewed in the redis.windows.conf configuration file)
[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

   Hey, come here first. . . .




A preliminary study of using Redis in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.