[Simple use of Java learning bit]jedis

Source: Internet
Author: User

Environment:

Idea, Jedis 2.8.0, Windows 7SP1

To introduce a jar package:

      <dependency>            <groupId>redis.clients</groupId>            <artifactid>jedis</artifactid >            <version>2.8.0</version>        </dependency>

Encapsulates a simple class that can be used for distribution and introduces a connection pool

 Public Final classJedisutils {Private StaticShardedjedispool Shardedjedispool; Privatejedisutils () {}/*** Single-instance object *@return     */     Public StaticShardedjedispool Instance () {if(Shardedjedispool! =NULL)returnShardedjedispool; Else{Shardedjedispool=Getshardedjedispool (); returnShardedjedispool; }    }    /**     *     * @return     */    Private StaticShardedjedispool Getshardedjedispool () {//generate a list of multi-machine connection information, in general, should be obtained from configuration files or other places, such as zookeeperlist<jedisshardinfo> shards =NewArraylist<jedisshardinfo>(); Shards.add (NewJedisshardinfo ("127.0.0.1", 6039)); Shards.add (NewJedisshardinfo ("127.0.0.1", 6040)); //Generate connection pool configuration informationJedispoolconfig config =NewJedispoolconfig (); Config.setmaxidle (10);//Maximum number of idle connectionsConfig.setmaxtotal (30);//Maximum number of connectionsConfig.setmaxwaitmillis (3 * 1000);//The maximum number of wait milliseconds to get a connection (if blockwhenexhausted is set to blocked), if time-out throws an exception, less than 0: blocking indeterminate time, default-1Config.settestwhileidle (true);//Config.settestonborrow (false);//check validity when getting a connection, default false, performance considerations, formal environment falseConfig.settestonreturn (false);//performance considerations, formal environment is false//generate a connection pool when the application is initialized        return Newshardedjedispool (config, shards); }    /*** Release the connection pool resource when the app is closed *@paramPool*/     Public voidPooldestroy (Shardedjedispool pool) {Pool.destroy (); }}

Business Scenario:

 Public classJedistest {Private Final StaticLogger Logger = Loggerfactory.getlogger (Loop.class);  Publicjedistest () {}/**     * @paramKey *@return     */     Publicstring GetValue (String key) {//get a connection from a connection pool when a business operationShardedjedis client =jedisutils.instance (). GetResource (); Try{String value=Client.get (key); System.out.println (String.Format ("Get command Execution Result:%s", value)); returnvalue; } Catch(Exception e) {//Todo:handle ExceptionLogger.error ( This. GetClass (). toString (), E.getmessage ()); } finally {            //the business operation completes and the connection is returned to the connection pool            if(NULL!=client)            {Client.close (); }        } //End of Try block        return""; }    /**     * @paramKey *@paramValue *@return     */     Public BooleanSetValue (string key, String value) {//get a connection from a connection pool when a business operationShardedjedis client =jedisutils.instance (). GetResource (); Try{String result=Client.set (key, value); System.out.println (String.Format ("SET command execution Result:%s", result)); return true; } Catch(Exception e) {logger.error ( This. GetClass (). toString (), E.getmessage ()); } finally {            //the business operation completes and the connection is returned to the connection pool            if(NULL!=client)            {Client.close (); }        } //End of Try block        return false; }    /*** Clean the cache according to key *@paramKey *@return     */     Public BooleanDelkey (String key) {//get a connection from a connection pool when a business operationShardedjedis client =jedisutils.instance (). GetResource (); Try{Long result=Client.del (key); System.out.println (String.Format ("Del instruction execution result:%s", result)); return true; } Catch(Exception e) {//Todo:handle ExceptionLogger.error ( This. GetClass (). toString (), E.getmessage ()); } finally {            //the business operation completes and the connection is returned to the connection pool            if(NULL!=client)            {Client.close (); }        } //End of Try block        return false; }

Test Case:

 Public classjedistest {@Test Public voidjedis_setvalue_test () {com.hager.javalearning.lessions.lessionjedis.JedisTest jedistest=Newcom.hager.javalearning.lessions.lessionjedis.JedisTest (); Booleanresult = Jedistest.setvalue ("test.1125", "Hello World".));    Assert.asserttrue (result); } @Test Public voidjedis_getvalue_test () {com.hager.javalearning.lessions.lessionjedis.JedisTest jedistest=Newcom.hager.javalearning.lessions.lessionjedis.JedisTest (); String result= Jedistest.getvalue ("test.1125"); String Hoperesult= "Hello world.";    Assert.assertequals (Hoperesult, result); } @Test Public voidjedis_delkey_test () {com.hager.javalearning.lessions.lessionjedis.JedisTest jedistest=Newcom.hager.javalearning.lessions.lessionjedis.JedisTest (); Booleanresult = Jedistest.delkey ("test.1125");        Assert.asserttrue (result); String Cacheresult=jedistest.getvalue ("test.1125");    Assert.assertnull (Cacheresult); }

=========

In addition, recently also learning Java basic knowledge, the last two days can remember, also recorded it:

1. Basic type and reference type:

The feeling base type is similar to the value type in C #, including the Byte,short,int,long,float,double,boolean,char character type 8 kinds;

Reference types, classes, interfaces, arrays

                              ┏ numeric ━┳━ integer type: byte short int long
┏ basic Data type ━━┫ ┗━ floating-point type: float double
┃ ┣ character type: Char
Data type ╋ ┗ Boolean: Boolean
┃ ┏ Classes (Class)
┗ Reference data Type ━━╋ Interface (interface)
┗ Arrays (Array)

2, inheritance, keyword extends: Follow the "Two with two small One big": (Li Gang's Java Crazy Lecture notes)

Two identical: The method name, the formal parameter list is same;

Two small: The subclass method return value type should be smaller or equal than the return value type of the parent class;

A large, refers to the access rights of the subclass, greater or equal access to the parent class; (That's private,public,protected, these things)

Reference:

http://aofengblog.blog.163.com/blog/static/631702120147298317919/

[Simple use of Java learning bit]jedis

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.