Compare commits

...

16 Commits

Author SHA1 Message Date
3817f4c7ed Replace tabs with spaces 2015-09-01 13:13:24 +01:00
cdd16a53af Move to new license, keep old for reference 2015-06-11 23:00:23 +01:00
81ba28a7b6 Update build.gradle to build artifact com.github.boukefalos:jlibredis:2.6.2 with gradle wrapper 2.2 2014-11-30 11:51:44 +00:00
Jungtaek Lim
bd2f12c04e bump up version 2014-11-25 21:36:59 +09:00
Tobias Ara Svensson
3257827f01 Fixes #791 Exceptions in close cause empty JedisPool and then deadlock 2014-11-24 12:23:42 +01:00
Marcos Nils
0c9c4c8b79 Merge pull request #774 from asikkema/cluster_incryByFloat
Adds incrByFloat as cluster command
2014-11-16 18:40:42 -03:00
rdifalco
59a13121ab Addresses issues #779 and #775.
Conflicts:
	src/main/java/redis/clients/jedis/Protocol.java
2014-11-14 09:49:46 +09:00
Jungtaek Lim
5d0f75a32f Merge branch 'master' of github.com:rdifalco/jedis into rdifalco-master
Conflicts:
	src/main/java/redis/clients/jedis/BinaryJedis.java
2014-11-13 13:20:59 +09:00
Marcos Lilljedahl
f9fb8843df Fixes #786 2014-11-12 11:17:43 -03:00
Jungtaek Lim
47da7a12ea Merge branch 'HeartSaVioR-jedis-pubsub-adaptor' 2014-11-11 08:00:39 +09:00
Jungtaek Lim
57d2e2ea05 Merge branch 'jedis-pubsub-adaptor' of github.com:HeartSaVioR/jedis into HeartSaVioR-jedis-pubsub-adaptor 2014-11-11 08:00:32 +09:00
Jungtaek Lim
8a33ab6e9a Remove Adaptor and update their own class (PubSub) 2014-11-07 23:11:43 +09:00
Jungtaek Lim
4ecca016a5 Introduce (Binary)JedisPubSubAdaptor
* Actually it's in JedisSentinelPool but not exposed to users
2014-11-04 22:42:17 +09:00
Albert Sikkema
d6850457bf Adds incrByFloat as cluster command 2014-10-20 11:17:23 +02:00
rdifalco
076df8c92d Expanded deprecated comment, fixed a misspelling of DECRBY. 2014-10-19 13:22:17 -07:00
rdifalco
8f4dbaf89f Fixed infinite timeout handling. Increased code reuse so that there will be fewer copy and paste errors. 2014-10-18 12:22:07 -07:00
123 changed files with 13656 additions and 13038 deletions

1
.gitignore vendored
View File

@@ -12,3 +12,4 @@ tags
.idea
*.aof
*.rdb
.maven

619
LICENSE Normal file
View File

@@ -0,0 +1,619 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

View File

@@ -2,9 +2,9 @@ apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'eclipse'
group = 'com.googlecode.jedis'
archivesBaseName = 'jedis'
version = '1.5.0'
group = 'com.github.boukefalos'
archivesBaseName = 'jlibredis'
version = '2.6.2'
repositories {
mavenCentral()
@@ -15,19 +15,12 @@ dependencies {
compile 'org.apache.commons:commons-pool2:2.0'
}
task wrapper(type: Wrapper) {
gradleVersion = '2.2'
}
/*
TODO: Customize for deployment
uploadArchives {
repositories.mavenDeployer {
repository(url: "file://localhost/repo/") {
authentication(userName: "user", password: "pass")
}
}
}
*/
task createWrapper(type: Wrapper) {
gradleVersion = '1.8'
}
repositories.mavenDeployer {
repository(url: uri('.maven'))
}
}

View File

@@ -1,6 +1,6 @@
#Mon Nov 04 18:13:13 EST 2013
#Sun Nov 30 11:33:11 GMT 2014
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-bin.zip
distributionUrl=http\://services.gradle.org/distributions/gradle-2.2-bin.zip

View File

@@ -9,7 +9,7 @@
<packaging>jar</packaging>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.1-SNAPSHOT</version>
<version>2.6.2-SNAPSHOT</version>
<name>Jedis</name>
<description>Jedis is a blazingly small and sane Redis java client.</description>
<url>https://github.com/xetorthio/jedis</url>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -158,38 +158,38 @@ public interface BinaryJedisCommands {
Set<byte[]> zrevrangeByScore(byte[] key, double max, double min);
Set<byte[]> zrangeByScore(byte[] key, double min, double max, int offset,
int count);
int count);
Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min);
Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset,
int count);
int count);
Set<byte[]> zrevrangeByScore(byte[] key, double max, double min,
int offset, int count);
int offset, int count);
Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min);
Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max,
int offset, int count);
int offset, int count);
Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min,
int offset, int count);
int offset, int count);
Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min);
Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max,
int offset, int count);
int offset, int count);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min,
int offset, int count);
int offset, int count);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min,
int offset, int count);
int offset, int count);
Long zremrangeByRank(byte[] key, long start, long end);
@@ -202,25 +202,35 @@ public interface BinaryJedisCommands {
Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max);
Set<byte[]> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max, int offset, int count);
final byte[] max, int offset, int count);
Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min);
final byte[] min);
Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min, int offset, int count);
final byte[] min, int offset, int count);
Long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max);
Long linsert(byte[] key, Client.LIST_POSITION where, byte[] pivot,
byte[] value);
byte[] value);
Long lpushx(byte[] key, byte[]... arg);
Long rpushx(byte[] key, byte[]... arg);
/**
* @deprecated unusable command, this command will be removed in 3.0.0.
*/
@Deprecated
List<byte[]> blpop(byte[] arg);
/**
* @deprecated unusable command, this command will be removed in 3.0.0.
*/
@Deprecated
List<byte[]> brpop(byte[] arg);
Long del(byte[] key);

View File

@@ -16,105 +16,104 @@ public abstract class BinaryJedisPubSub {
private int subscribedChannels = 0;
private Client client;
public abstract void onMessage(byte[] channel, byte[] message);
public void onMessage(byte[] channel, byte[] message) {}
public abstract void onPMessage(byte[] pattern, byte[] channel,
byte[] message);
public void onPMessage(byte[] pattern, byte[] channel, byte[] message) {}
public abstract void onSubscribe(byte[] channel, int subscribedChannels);
public void onSubscribe(byte[] channel, int subscribedChannels) {}
public abstract void onUnsubscribe(byte[] channel, int subscribedChannels);
public void onUnsubscribe(byte[] channel, int subscribedChannels) {}
public abstract void onPUnsubscribe(byte[] pattern, int subscribedChannels);
public void onPUnsubscribe(byte[] pattern, int subscribedChannels) {}
public abstract void onPSubscribe(byte[] pattern, int subscribedChannels);
public void onPSubscribe(byte[] pattern, int subscribedChannels) {}
public void unsubscribe() {
client.unsubscribe();
client.flush();
client.unsubscribe();
client.flush();
}
public void unsubscribe(byte[]... channels) {
client.unsubscribe(channels);
client.flush();
client.unsubscribe(channels);
client.flush();
}
public void subscribe(byte[]... channels) {
client.subscribe(channels);
client.flush();
client.subscribe(channels);
client.flush();
}
public void psubscribe(byte[]... patterns) {
client.psubscribe(patterns);
client.flush();
client.psubscribe(patterns);
client.flush();
}
public void punsubscribe() {
client.punsubscribe();
client.flush();
client.punsubscribe();
client.flush();
}
public void punsubscribe(byte[]... patterns) {
client.punsubscribe(patterns);
client.flush();
client.punsubscribe(patterns);
client.flush();
}
public boolean isSubscribed() {
return subscribedChannels > 0;
return subscribedChannels > 0;
}
public void proceedWithPatterns(Client client, byte[]... patterns) {
this.client = client;
client.psubscribe(patterns);
process(client);
this.client = client;
client.psubscribe(patterns);
process(client);
}
public void proceed(Client client, byte[]... channels) {
this.client = client;
client.subscribe(channels);
process(client);
this.client = client;
client.subscribe(channels);
process(client);
}
private void process(Client client) {
do {
List<Object> reply = client.getObjectMultiBulkReply();
final Object firstObj = reply.get(0);
if (!(firstObj instanceof byte[])) {
throw new JedisException("Unknown message type: " + firstObj);
}
final byte[] resp = (byte[]) firstObj;
if (Arrays.equals(SUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1);
onSubscribe(bchannel, subscribedChannels);
} else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1);
onUnsubscribe(bchannel, subscribedChannels);
} else if (Arrays.equals(MESSAGE.raw, resp)) {
final byte[] bchannel = (byte[]) reply.get(1);
final byte[] bmesg = (byte[]) reply.get(2);
onMessage(bchannel, bmesg);
} else if (Arrays.equals(PMESSAGE.raw, resp)) {
final byte[] bpattern = (byte[]) reply.get(1);
final byte[] bchannel = (byte[]) reply.get(2);
final byte[] bmesg = (byte[]) reply.get(3);
onPMessage(bpattern, bchannel, bmesg);
} else if (Arrays.equals(PSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1);
onPSubscribe(bpattern, subscribedChannels);
} else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1);
onPUnsubscribe(bpattern, subscribedChannels);
} else {
throw new JedisException("Unknown message type: " + firstObj);
}
} while (isSubscribed());
do {
List<Object> reply = client.getObjectMultiBulkReply();
final Object firstObj = reply.get(0);
if (!(firstObj instanceof byte[])) {
throw new JedisException("Unknown message type: " + firstObj);
}
final byte[] resp = (byte[]) firstObj;
if (Arrays.equals(SUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1);
onSubscribe(bchannel, subscribedChannels);
} else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1);
onUnsubscribe(bchannel, subscribedChannels);
} else if (Arrays.equals(MESSAGE.raw, resp)) {
final byte[] bchannel = (byte[]) reply.get(1);
final byte[] bmesg = (byte[]) reply.get(2);
onMessage(bchannel, bmesg);
} else if (Arrays.equals(PMESSAGE.raw, resp)) {
final byte[] bpattern = (byte[]) reply.get(1);
final byte[] bchannel = (byte[]) reply.get(2);
final byte[] bmesg = (byte[]) reply.get(3);
onPMessage(bpattern, bchannel, bmesg);
} else if (Arrays.equals(PSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1);
onPSubscribe(bpattern, subscribedChannels);
} else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1);
onPUnsubscribe(bpattern, subscribedChannels);
} else {
throw new JedisException("Unknown message type: " + firstObj);
}
} while (isSubscribed());
}
public int getSubscribedChannels() {
return subscribedChannels;
return subscribedChannels;
}
}

View File

@@ -67,7 +67,7 @@ public interface BinaryRedisPipeline {
Response<byte[]> lindex(byte[] key, long index);
Response<Long> linsert(byte[] key, BinaryClient.LIST_POSITION where,
byte[] pivot, byte[] value);
byte[] pivot, byte[] value);
Response<Long> llen(byte[] key);
@@ -148,44 +148,44 @@ public interface BinaryRedisPipeline {
Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min, byte[] max);
Response<Set<byte[]>> zrangeByScore(byte[] key, double min, double max,
int offset, int count);
int offset, int count);
Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min, byte[] max,
int offset, int count);
int offset, int count);
Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, double min,
double max);
double max);
Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, byte[] min,
byte[] max);
byte[] max);
Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, double min,
double max, int offset, int count);
double max, int offset, int count);
Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, byte[] min,
byte[] max, int offset, int count);
byte[] max, int offset, int count);
Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max, double min);
Response<Set<byte[]>> zrevrangeByScore(byte[] key, byte[] max, byte[] min);
Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max, double min,
int offset, int count);
int offset, int count);
Response<Set<byte[]>> zrevrangeByScore(byte[] key, byte[] max, byte[] min,
int offset, int count);
int offset, int count);
Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, double max,
double min);
double min);
Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, byte[] max,
byte[] min);
byte[] min);
Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, double max,
double min, int offset, int count);
double min, int offset, int count);
Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, byte[] max,
byte[] min, int offset, int count);
byte[] min, int offset, int count);
Response<Set<Tuple>> zrangeWithScores(byte[] key, long start, long end);
@@ -208,22 +208,22 @@ public interface BinaryRedisPipeline {
Response<Double> zscore(byte[] key, byte[] member);
Response<Long> zlexcount(final byte[] key, final byte[] min,
final byte[] max);
final byte[] max);
Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max);
final byte[] max);
Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max, int offset, int count);
final byte[] max, int offset, int count);
Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min);
final byte[] min);
Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min, int offset, int count);
final byte[] min, int offset, int count);
Response<Long> zremrangeByLex(final byte[] key, final byte[] min,
final byte[] max);
final byte[] max);
Response<Long> bitcount(byte[] key);

View File

@@ -11,618 +11,618 @@ import redis.clients.util.Hashing;
import redis.clients.util.Sharded;
public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
implements BinaryJedisCommands {
implements BinaryJedisCommands {
public BinaryShardedJedis(List<JedisShardInfo> shards) {
super(shards);
super(shards);
}
public BinaryShardedJedis(List<JedisShardInfo> shards, Hashing algo) {
super(shards, algo);
super(shards, algo);
}
public BinaryShardedJedis(List<JedisShardInfo> shards, Pattern keyTagPattern) {
super(shards, keyTagPattern);
super(shards, keyTagPattern);
}
public BinaryShardedJedis(List<JedisShardInfo> shards, Hashing algo,
Pattern keyTagPattern) {
super(shards, algo, keyTagPattern);
Pattern keyTagPattern) {
super(shards, algo, keyTagPattern);
}
public void disconnect() {
for (Jedis jedis : getAllShards()) {
jedis.quit();
jedis.disconnect();
}
for (Jedis jedis : getAllShards()) {
jedis.quit();
jedis.disconnect();
}
}
protected Jedis create(JedisShardInfo shard) {
return new Jedis(shard);
return new Jedis(shard);
}
public String set(byte[] key, byte[] value) {
Jedis j = getShard(key);
return j.set(key, value);
Jedis j = getShard(key);
return j.set(key, value);
}
public byte[] get(byte[] key) {
Jedis j = getShard(key);
return j.get(key);
Jedis j = getShard(key);
return j.get(key);
}
public Boolean exists(byte[] key) {
Jedis j = getShard(key);
return j.exists(key);
Jedis j = getShard(key);
return j.exists(key);
}
public String type(byte[] key) {
Jedis j = getShard(key);
return j.type(key);
Jedis j = getShard(key);
return j.type(key);
}
public Long expire(byte[] key, int seconds) {
Jedis j = getShard(key);
return j.expire(key, seconds);
Jedis j = getShard(key);
return j.expire(key, seconds);
}
public Long expireAt(byte[] key, long unixTime) {
Jedis j = getShard(key);
return j.expireAt(key, unixTime);
Jedis j = getShard(key);
return j.expireAt(key, unixTime);
}
public Long ttl(byte[] key) {
Jedis j = getShard(key);
return j.ttl(key);
Jedis j = getShard(key);
return j.ttl(key);
}
public byte[] getSet(byte[] key, byte[] value) {
Jedis j = getShard(key);
return j.getSet(key, value);
Jedis j = getShard(key);
return j.getSet(key, value);
}
public Long setnx(byte[] key, byte[] value) {
Jedis j = getShard(key);
return j.setnx(key, value);
Jedis j = getShard(key);
return j.setnx(key, value);
}
public String setex(byte[] key, int seconds, byte[] value) {
Jedis j = getShard(key);
return j.setex(key, seconds, value);
Jedis j = getShard(key);
return j.setex(key, seconds, value);
}
public Long decrBy(byte[] key, long integer) {
Jedis j = getShard(key);
return j.decrBy(key, integer);
Jedis j = getShard(key);
return j.decrBy(key, integer);
}
public Long decr(byte[] key) {
Jedis j = getShard(key);
return j.decr(key);
Jedis j = getShard(key);
return j.decr(key);
}
public Long del(byte[] key) {
Jedis j = getShard(key);
return j.del(key);
Jedis j = getShard(key);
return j.del(key);
}
public Long incrBy(byte[] key, long integer) {
Jedis j = getShard(key);
return j.incrBy(key, integer);
Jedis j = getShard(key);
return j.incrBy(key, integer);
}
public Double incrByFloat(byte[] key, double integer) {
Jedis j = getShard(key);
return j.incrByFloat(key, integer);
Jedis j = getShard(key);
return j.incrByFloat(key, integer);
}
public Long incr(byte[] key) {
Jedis j = getShard(key);
return j.incr(key);
Jedis j = getShard(key);
return j.incr(key);
}
public Long append(byte[] key, byte[] value) {
Jedis j = getShard(key);
return j.append(key, value);
Jedis j = getShard(key);
return j.append(key, value);
}
public byte[] substr(byte[] key, int start, int end) {
Jedis j = getShard(key);
return j.substr(key, start, end);
Jedis j = getShard(key);
return j.substr(key, start, end);
}
public Long hset(byte[] key, byte[] field, byte[] value) {
Jedis j = getShard(key);
return j.hset(key, field, value);
Jedis j = getShard(key);
return j.hset(key, field, value);
}
public byte[] hget(byte[] key, byte[] field) {
Jedis j = getShard(key);
return j.hget(key, field);
Jedis j = getShard(key);
return j.hget(key, field);
}
public Long hsetnx(byte[] key, byte[] field, byte[] value) {
Jedis j = getShard(key);
return j.hsetnx(key, field, value);
Jedis j = getShard(key);
return j.hsetnx(key, field, value);
}
public String hmset(byte[] key, Map<byte[], byte[]> hash) {
Jedis j = getShard(key);
return j.hmset(key, hash);
Jedis j = getShard(key);
return j.hmset(key, hash);
}
public List<byte[]> hmget(byte[] key, byte[]... fields) {
Jedis j = getShard(key);
return j.hmget(key, fields);
Jedis j = getShard(key);
return j.hmget(key, fields);
}
public Long hincrBy(byte[] key, byte[] field, long value) {
Jedis j = getShard(key);
return j.hincrBy(key, field, value);
Jedis j = getShard(key);
return j.hincrBy(key, field, value);
}
public Double hincrByFloat(byte[] key, byte[] field, double value) {
Jedis j = getShard(key);
return j.hincrByFloat(key, field, value);
Jedis j = getShard(key);
return j.hincrByFloat(key, field, value);
}
public Boolean hexists(byte[] key, byte[] field) {
Jedis j = getShard(key);
return j.hexists(key, field);
Jedis j = getShard(key);
return j.hexists(key, field);
}
public Long hdel(byte[] key, byte[]... fields) {
Jedis j = getShard(key);
return j.hdel(key, fields);
Jedis j = getShard(key);
return j.hdel(key, fields);
}
public Long hlen(byte[] key) {
Jedis j = getShard(key);
return j.hlen(key);
Jedis j = getShard(key);
return j.hlen(key);
}
public Set<byte[]> hkeys(byte[] key) {
Jedis j = getShard(key);
return j.hkeys(key);
Jedis j = getShard(key);
return j.hkeys(key);
}
public Collection<byte[]> hvals(byte[] key) {
Jedis j = getShard(key);
return j.hvals(key);
Jedis j = getShard(key);
return j.hvals(key);
}
public Map<byte[], byte[]> hgetAll(byte[] key) {
Jedis j = getShard(key);
return j.hgetAll(key);
Jedis j = getShard(key);
return j.hgetAll(key);
}
public Long rpush(byte[] key, byte[]... strings) {
Jedis j = getShard(key);
return j.rpush(key, strings);
Jedis j = getShard(key);
return j.rpush(key, strings);
}
public Long lpush(byte[] key, byte[]... strings) {
Jedis j = getShard(key);
return j.lpush(key, strings);
Jedis j = getShard(key);
return j.lpush(key, strings);
}
public Long strlen(final byte[] key) {
Jedis j = getShard(key);
return j.strlen(key);
Jedis j = getShard(key);
return j.strlen(key);
}
public Long lpushx(byte[] key, byte[]... string) {
Jedis j = getShard(key);
return j.lpushx(key, string);
Jedis j = getShard(key);
return j.lpushx(key, string);
}
public Long persist(final byte[] key) {
Jedis j = getShard(key);
return j.persist(key);
Jedis j = getShard(key);
return j.persist(key);
}
public Long rpushx(byte[] key, byte[]... string) {
Jedis j = getShard(key);
return j.rpushx(key, string);
Jedis j = getShard(key);
return j.rpushx(key, string);
}
public Long llen(byte[] key) {
Jedis j = getShard(key);
return j.llen(key);
Jedis j = getShard(key);
return j.llen(key);
}
public List<byte[]> lrange(byte[] key, long start, long end) {
Jedis j = getShard(key);
return j.lrange(key, start, end);
Jedis j = getShard(key);
return j.lrange(key, start, end);
}
public String ltrim(byte[] key, long start, long end) {
Jedis j = getShard(key);
return j.ltrim(key, start, end);
Jedis j = getShard(key);
return j.ltrim(key, start, end);
}
public byte[] lindex(byte[] key, long index) {
Jedis j = getShard(key);
return j.lindex(key, index);
Jedis j = getShard(key);
return j.lindex(key, index);
}
public String lset(byte[] key, long index, byte[] value) {
Jedis j = getShard(key);
return j.lset(key, index, value);
Jedis j = getShard(key);
return j.lset(key, index, value);
}
public Long lrem(byte[] key, long count, byte[] value) {
Jedis j = getShard(key);
return j.lrem(key, count, value);
Jedis j = getShard(key);
return j.lrem(key, count, value);
}
public byte[] lpop(byte[] key) {
Jedis j = getShard(key);
return j.lpop(key);
Jedis j = getShard(key);
return j.lpop(key);
}
public byte[] rpop(byte[] key) {
Jedis j = getShard(key);
return j.rpop(key);
Jedis j = getShard(key);
return j.rpop(key);
}
public Long sadd(byte[] key, byte[]... members) {
Jedis j = getShard(key);
return j.sadd(key, members);
Jedis j = getShard(key);
return j.sadd(key, members);
}
public Set<byte[]> smembers(byte[] key) {
Jedis j = getShard(key);
return j.smembers(key);
Jedis j = getShard(key);
return j.smembers(key);
}
public Long srem(byte[] key, byte[]... members) {
Jedis j = getShard(key);
return j.srem(key, members);
Jedis j = getShard(key);
return j.srem(key, members);
}
public byte[] spop(byte[] key) {
Jedis j = getShard(key);
return j.spop(key);
Jedis j = getShard(key);
return j.spop(key);
}
public Long scard(byte[] key) {
Jedis j = getShard(key);
return j.scard(key);
Jedis j = getShard(key);
return j.scard(key);
}
public Boolean sismember(byte[] key, byte[] member) {
Jedis j = getShard(key);
return j.sismember(key, member);
Jedis j = getShard(key);
return j.sismember(key, member);
}
public byte[] srandmember(byte[] key) {
Jedis j = getShard(key);
return j.srandmember(key);
Jedis j = getShard(key);
return j.srandmember(key);
}
@Override
public List srandmember(byte[] key, int count) {
Jedis j = getShard(key);
return j.srandmember(key, count);
Jedis j = getShard(key);
return j.srandmember(key, count);
}
public Long zadd(byte[] key, double score, byte[] member) {
Jedis j = getShard(key);
return j.zadd(key, score, member);
Jedis j = getShard(key);
return j.zadd(key, score, member);
}
public Long zadd(byte[] key, Map<byte[], Double> scoreMembers) {
Jedis j = getShard(key);
return j.zadd(key, scoreMembers);
Jedis j = getShard(key);
return j.zadd(key, scoreMembers);
}
public Set<byte[]> zrange(byte[] key, long start, long end) {
Jedis j = getShard(key);
return j.zrange(key, start, end);
Jedis j = getShard(key);
return j.zrange(key, start, end);
}
public Long zrem(byte[] key, byte[]... members) {
Jedis j = getShard(key);
return j.zrem(key, members);
Jedis j = getShard(key);
return j.zrem(key, members);
}
public Double zincrby(byte[] key, double score, byte[] member) {
Jedis j = getShard(key);
return j.zincrby(key, score, member);
Jedis j = getShard(key);
return j.zincrby(key, score, member);
}
public Long zrank(byte[] key, byte[] member) {
Jedis j = getShard(key);
return j.zrank(key, member);
Jedis j = getShard(key);
return j.zrank(key, member);
}
public Long zrevrank(byte[] key, byte[] member) {
Jedis j = getShard(key);
return j.zrevrank(key, member);
Jedis j = getShard(key);
return j.zrevrank(key, member);
}
public Set<byte[]> zrevrange(byte[] key, long start, long end) {
Jedis j = getShard(key);
return j.zrevrange(key, start, end);
Jedis j = getShard(key);
return j.zrevrange(key, start, end);
}
public Set<Tuple> zrangeWithScores(byte[] key, long start, long end) {
Jedis j = getShard(key);
return j.zrangeWithScores(key, start, end);
Jedis j = getShard(key);
return j.zrangeWithScores(key, start, end);
}
public Set<Tuple> zrevrangeWithScores(byte[] key, long start, long end) {
Jedis j = getShard(key);
return j.zrevrangeWithScores(key, start, end);
Jedis j = getShard(key);
return j.zrevrangeWithScores(key, start, end);
}
public Long zcard(byte[] key) {
Jedis j = getShard(key);
return j.zcard(key);
Jedis j = getShard(key);
return j.zcard(key);
}
public Double zscore(byte[] key, byte[] member) {
Jedis j = getShard(key);
return j.zscore(key, member);
Jedis j = getShard(key);
return j.zscore(key, member);
}
public List<byte[]> sort(byte[] key) {
Jedis j = getShard(key);
return j.sort(key);
Jedis j = getShard(key);
return j.sort(key);
}
public List<byte[]> sort(byte[] key, SortingParams sortingParameters) {
Jedis j = getShard(key);
return j.sort(key, sortingParameters);
Jedis j = getShard(key);
return j.sort(key, sortingParameters);
}
public Long zcount(byte[] key, double min, double max) {
Jedis j = getShard(key);
return j.zcount(key, min, max);
Jedis j = getShard(key);
return j.zcount(key, min, max);
}
public Long zcount(byte[] key, byte[] min, byte[] max) {
Jedis j = getShard(key);
return j.zcount(key, min, max);
Jedis j = getShard(key);
return j.zcount(key, min, max);
}
public Set<byte[]> zrangeByScore(byte[] key, double min, double max) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max);
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max);
}
public Set<byte[]> zrangeByScore(byte[] key, double min, double max,
int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count);
int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count);
}
public Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max);
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max);
}
public Set<Tuple> zrangeByScoreWithScores(byte[] key, double min,
double max, int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count);
double max, int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count);
}
public Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max);
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max);
}
public Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max);
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max);
}
public Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min,
byte[] max, int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count);
byte[] max, int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count);
}
public Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max,
int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count);
int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count);
}
public Set<byte[]> zrevrangeByScore(byte[] key, double max, double min) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min);
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min);
}
public Set<byte[]> zrevrangeByScore(byte[] key, double max, double min,
int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count);
int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count);
}
public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max,
double min) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min);
double min) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min);
}
public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max,
double min, int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
double min, int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
}
public Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min);
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min);
}
public Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min,
int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count);
int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count);
}
public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max,
byte[] min) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min);
byte[] min) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min);
}
public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max,
byte[] min, int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
byte[] min, int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
}
public Long zremrangeByRank(byte[] key, long start, long end) {
Jedis j = getShard(key);
return j.zremrangeByRank(key, start, end);
Jedis j = getShard(key);
return j.zremrangeByRank(key, start, end);
}
public Long zremrangeByScore(byte[] key, double start, double end) {
Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end);
Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end);
}
public Long zremrangeByScore(byte[] key, byte[] start, byte[] end) {
Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end);
Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end);
}
@Override
public Long zlexcount(final byte[] key, final byte[] min, final byte[] max) {
Jedis j = getShard(key);
return j.zlexcount(key, min, max);
Jedis j = getShard(key);
return j.zlexcount(key, min, max);
}
@Override
public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max) {
Jedis j = getShard(key);
return j.zrangeByLex(key, min, max);
final byte[] max) {
Jedis j = getShard(key);
return j.zrangeByLex(key, min, max);
}
@Override
public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max, final int offset, final int count) {
Jedis j = getShard(key);
return j.zrangeByLex(key, min, max, offset, count);
final byte[] max, final int offset, final int count) {
Jedis j = getShard(key);
return j.zrangeByLex(key, min, max, offset, count);
}
@Override
public Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min) {
Jedis j = getShard(key);
return j.zrevrangeByLex(key, max, min);
Jedis j = getShard(key);
return j.zrevrangeByLex(key, max, min);
}
@Override
public Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min,
int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByLex(key, max, min, offset, count);
int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByLex(key, max, min, offset, count);
}
@Override
public Long zremrangeByLex(final byte[] key, final byte[] min,
final byte[] max) {
Jedis j = getShard(key);
return j.zremrangeByLex(key, min, max);
final byte[] max) {
Jedis j = getShard(key);
return j.zremrangeByLex(key, min, max);
}
public Long linsert(byte[] key, LIST_POSITION where, byte[] pivot,
byte[] value) {
Jedis j = getShard(key);
return j.linsert(key, where, pivot, value);
byte[] value) {
Jedis j = getShard(key);
return j.linsert(key, where, pivot, value);
}
public ShardedJedisPipeline pipelined() {
ShardedJedisPipeline pipeline = new ShardedJedisPipeline();
pipeline.setShardedJedis(this);
return pipeline;
ShardedJedisPipeline pipeline = new ShardedJedisPipeline();
pipeline.setShardedJedis(this);
return pipeline;
}
public Long objectRefcount(byte[] key) {
Jedis j = getShard(key);
return j.objectRefcount(key);
Jedis j = getShard(key);
return j.objectRefcount(key);
}
public byte[] objectEncoding(byte[] key) {
Jedis j = getShard(key);
return j.objectEncoding(key);
Jedis j = getShard(key);
return j.objectEncoding(key);
}
public Long objectIdletime(byte[] key) {
Jedis j = getShard(key);
return j.objectIdletime(key);
Jedis j = getShard(key);
return j.objectIdletime(key);
}
public Boolean setbit(byte[] key, long offset, boolean value) {
Jedis j = getShard(key);
return j.setbit(key, offset, value);
Jedis j = getShard(key);
return j.setbit(key, offset, value);
}
public Boolean setbit(byte[] key, long offset, byte[] value) {
Jedis j = getShard(key);
return j.setbit(key, offset, value);
Jedis j = getShard(key);
return j.setbit(key, offset, value);
}
public Boolean getbit(byte[] key, long offset) {
Jedis j = getShard(key);
return j.getbit(key, offset);
Jedis j = getShard(key);
return j.getbit(key, offset);
}
public Long setrange(byte[] key, long offset, byte[] value) {
Jedis j = getShard(key);
return j.setrange(key, offset, value);
Jedis j = getShard(key);
return j.setrange(key, offset, value);
}
public byte[] getrange(byte[] key, long startOffset, long endOffset) {
Jedis j = getShard(key);
return j.getrange(key, startOffset, endOffset);
Jedis j = getShard(key);
return j.getrange(key, startOffset, endOffset);
}
public Long move(byte[] key, int dbIndex) {
Jedis j = getShard(key);
return j.move(key, dbIndex);
Jedis j = getShard(key);
return j.move(key, dbIndex);
}
public byte[] echo(byte[] arg) {
Jedis j = getShard(arg);
return j.echo(arg);
Jedis j = getShard(arg);
return j.echo(arg);
}
public List<byte[]> brpop(byte[] arg) {
Jedis j = getShard(arg);
return j.brpop(arg);
Jedis j = getShard(arg);
return j.brpop(arg);
}
public List<byte[]> blpop(byte[] arg) {
Jedis j = getShard(arg);
return j.blpop(arg);
Jedis j = getShard(arg);
return j.blpop(arg);
}
public Long bitcount(byte[] key) {
Jedis j = getShard(key);
return j.bitcount(key);
Jedis j = getShard(key);
return j.bitcount(key);
}
public Long bitcount(byte[] key, long start, long end) {
Jedis j = getShard(key);
return j.bitcount(key, start, end);
Jedis j = getShard(key);
return j.bitcount(key, start, end);
}
@Override
public Long pfadd(final byte[] key, final byte[]... elements) {
Jedis j = getShard(key);
return j.pfadd(key, elements);
Jedis j = getShard(key);
return j.pfadd(key, elements);
}
@Override
public long pfcount(final byte[] key) {
Jedis j = getShard(key);
return j.pfcount(key);
Jedis j = getShard(key);
return j.pfcount(key);
}
}

View File

@@ -12,16 +12,16 @@ public class BitPosParams {
}
public BitPosParams(long start) {
params.add(Protocol.toByteArray(start));
params.add(Protocol.toByteArray(start));
}
public BitPosParams(long start, long end) {
this(start);
this(start);
params.add(Protocol.toByteArray(end));
params.add(Protocol.toByteArray(end));
}
public Collection<byte[]> getParams() {
return Collections.unmodifiableCollection(params);
return Collections.unmodifiableCollection(params);
}
}

View File

@@ -14,265 +14,265 @@ import redis.clients.util.SafeEncoder;
public class BuilderFactory {
public static final Builder<Double> DOUBLE = new Builder<Double>() {
public Double build(Object data) {
String asString = STRING.build(data);
return asString == null ? null : Double.valueOf(asString);
}
public Double build(Object data) {
String asString = STRING.build(data);
return asString == null ? null : Double.valueOf(asString);
}
public String toString() {
return "double";
}
public String toString() {
return "double";
}
};
public static final Builder<Boolean> BOOLEAN = new Builder<Boolean>() {
public Boolean build(Object data) {
return ((Long) data) == 1;
}
public Boolean build(Object data) {
return ((Long) data) == 1;
}
public String toString() {
return "boolean";
}
public String toString() {
return "boolean";
}
};
public static final Builder<byte[]> BYTE_ARRAY = new Builder<byte[]>() {
public byte[] build(Object data) {
return ((byte[]) data); // deleted == 1
}
public byte[] build(Object data) {
return ((byte[]) data); // deleted == 1
}
public String toString() {
return "byte[]";
}
public String toString() {
return "byte[]";
}
};
public static final Builder<Long> LONG = new Builder<Long>() {
public Long build(Object data) {
return (Long) data;
}
public Long build(Object data) {
return (Long) data;
}
public String toString() {
return "long";
}
public String toString() {
return "long";
}
};
public static final Builder<String> STRING = new Builder<String>() {
public String build(Object data) {
return data == null ? null : SafeEncoder.encode((byte[]) data);
}
public String build(Object data) {
return data == null ? null : SafeEncoder.encode((byte[]) data);
}
public String toString() {
return "string";
}
public String toString() {
return "string";
}
};
public static final Builder<List<String>> STRING_LIST = new Builder<List<String>>() {
@SuppressWarnings("unchecked")
public List<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final ArrayList<String> result = new ArrayList<String>(l.size());
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
@SuppressWarnings("unchecked")
public List<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final ArrayList<String> result = new ArrayList<String>(l.size());
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
public String toString() {
return "List<String>";
}
public String toString() {
return "List<String>";
}
};
public static final Builder<Map<String, String>> STRING_MAP = new Builder<Map<String, String>>() {
@SuppressWarnings("unchecked")
public Map<String, String> build(Object data) {
final List<byte[]> flatHash = (List<byte[]>) data;
final Map<String, String> hash = new HashMap<String, String>();
final Iterator<byte[]> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(SafeEncoder.encode(iterator.next()),
SafeEncoder.encode(iterator.next()));
}
@SuppressWarnings("unchecked")
public Map<String, String> build(Object data) {
final List<byte[]> flatHash = (List<byte[]>) data;
final Map<String, String> hash = new HashMap<String, String>();
final Iterator<byte[]> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(SafeEncoder.encode(iterator.next()),
SafeEncoder.encode(iterator.next()));
}
return hash;
}
return hash;
}
public String toString() {
return "Map<String, String>";
}
public String toString() {
return "Map<String, String>";
}
};
public static final Builder<Map<String, String>> PUBSUB_NUMSUB_MAP = new Builder<Map<String, String>>() {
@SuppressWarnings("unchecked")
public Map<String, String> build(Object data) {
final List<Object> flatHash = (List<Object>) data;
final Map<String, String> hash = new HashMap<String, String>();
final Iterator<Object> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(SafeEncoder.encode((byte[]) iterator.next()),
String.valueOf((Long) iterator.next()));
}
@SuppressWarnings("unchecked")
public Map<String, String> build(Object data) {
final List<Object> flatHash = (List<Object>) data;
final Map<String, String> hash = new HashMap<String, String>();
final Iterator<Object> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(SafeEncoder.encode((byte[]) iterator.next()),
String.valueOf((Long) iterator.next()));
}
return hash;
}
return hash;
}
public String toString() {
return "PUBSUB_NUMSUB_MAP<String, String>";
}
public String toString() {
return "PUBSUB_NUMSUB_MAP<String, String>";
}
};
public static final Builder<Set<String>> STRING_SET = new Builder<Set<String>>() {
@SuppressWarnings("unchecked")
public Set<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<String> result = new HashSet<String>(l.size());
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
@SuppressWarnings("unchecked")
public Set<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<String> result = new HashSet<String>(l.size());
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
public String toString() {
return "Set<String>";
}
public String toString() {
return "Set<String>";
}
};
public static final Builder<List<byte[]>> BYTE_ARRAY_LIST = new Builder<List<byte[]>>() {
@SuppressWarnings("unchecked")
public List<byte[]> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
@SuppressWarnings("unchecked")
public List<byte[]> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
return l;
}
return l;
}
public String toString() {
return "List<byte[]>";
}
public String toString() {
return "List<byte[]>";
}
};
public static final Builder<Set<byte[]>> BYTE_ARRAY_ZSET = new Builder<Set<byte[]>>() {
@SuppressWarnings("unchecked")
public Set<byte[]> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<byte[]> result = new LinkedHashSet<byte[]>(l);
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(barray);
}
}
return result;
}
@SuppressWarnings("unchecked")
public Set<byte[]> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<byte[]> result = new LinkedHashSet<byte[]>(l);
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(barray);
}
}
return result;
}
public String toString() {
return "ZSet<byte[]>";
}
public String toString() {
return "ZSet<byte[]>";
}
};
public static final Builder<Map<byte[], byte[]>> BYTE_ARRAY_MAP = new Builder<Map<byte[], byte[]>>() {
@SuppressWarnings("unchecked")
public Map<byte[], byte[]> build(Object data) {
final List<byte[]> flatHash = (List<byte[]>) data;
final Map<byte[], byte[]> hash = new JedisByteHashMap();
final Iterator<byte[]> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(iterator.next(), iterator.next());
}
@SuppressWarnings("unchecked")
public Map<byte[], byte[]> build(Object data) {
final List<byte[]> flatHash = (List<byte[]>) data;
final Map<byte[], byte[]> hash = new JedisByteHashMap();
final Iterator<byte[]> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(iterator.next(), iterator.next());
}
return hash;
}
return hash;
}
public String toString() {
return "Map<byte[], byte[]>";
}
public String toString() {
return "Map<byte[], byte[]>";
}
};
public static final Builder<Set<String>> STRING_ZSET = new Builder<Set<String>>() {
@SuppressWarnings("unchecked")
public Set<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<String> result = new LinkedHashSet<String>(l.size());
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
@SuppressWarnings("unchecked")
public Set<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<String> result = new LinkedHashSet<String>(l.size());
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
public String toString() {
return "ZSet<String>";
}
public String toString() {
return "ZSet<String>";
}
};
public static final Builder<Set<Tuple>> TUPLE_ZSET = new Builder<Set<Tuple>>() {
@SuppressWarnings("unchecked")
public Set<Tuple> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size());
Iterator<byte[]> iterator = l.iterator();
while (iterator.hasNext()) {
result.add(new Tuple(SafeEncoder.encode(iterator.next()),
Double.valueOf(SafeEncoder.encode(iterator.next()))));
}
return result;
}
@SuppressWarnings("unchecked")
public Set<Tuple> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size());
Iterator<byte[]> iterator = l.iterator();
while (iterator.hasNext()) {
result.add(new Tuple(SafeEncoder.encode(iterator.next()),
Double.valueOf(SafeEncoder.encode(iterator.next()))));
}
return result;
}
public String toString() {
return "ZSet<Tuple>";
}
public String toString() {
return "ZSet<Tuple>";
}
};
public static final Builder<Set<Tuple>> TUPLE_ZSET_BINARY = new Builder<Set<Tuple>>() {
@SuppressWarnings("unchecked")
public Set<Tuple> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size());
Iterator<byte[]> iterator = l.iterator();
while (iterator.hasNext()) {
result.add(new Tuple(iterator.next(), Double
.valueOf(SafeEncoder.encode(iterator.next()))));
}
@SuppressWarnings("unchecked")
public Set<Tuple> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size());
Iterator<byte[]> iterator = l.iterator();
while (iterator.hasNext()) {
result.add(new Tuple(iterator.next(), Double
.valueOf(SafeEncoder.encode(iterator.next()))));
}
return result;
return result;
}
}
public String toString() {
return "ZSet<Tuple>";
}
public String toString() {
return "ZSet<Tuple>";
}
};
}

File diff suppressed because it is too large Load Diff

View File

@@ -9,7 +9,7 @@ public interface Commands {
public void set(final String key, final String value);
public void set(final String key, final String value, final String nxxx,
final String expx, final long time);
final String expx, final long time);
public void get(final String key);
@@ -82,7 +82,7 @@ public interface Commands {
public void hincrBy(final String key, final String field, final long value);
public void hincrByFloat(final String key, final String field,
final double value);
final double value);
public void hexists(final String key, final String field);
@@ -127,7 +127,7 @@ public interface Commands {
public void spop(final String key);
public void smove(final String srckey, final String dstkey,
final String member);
final String member);
public void scard(final String key);
@@ -156,7 +156,7 @@ public interface Commands {
public void zrem(final String key, final String... members);
public void zincrby(final String key, final double score,
final String member);
final String member);
public void zrank(final String key, final String member);
@@ -165,10 +165,10 @@ public interface Commands {
public void zrevrange(final String key, final long start, final long end);
public void zrangeWithScores(final String key, final long start,
final long end);
final long end);
public void zrevrangeWithScores(final String key, final long start,
final long end);
final long end);
public void zcard(final String key);
@@ -183,79 +183,79 @@ public interface Commands {
public void blpop(final String[] args);
public void sort(final String key, final SortingParams sortingParameters,
final String dstkey);
final String dstkey);
public void sort(final String key, final String dstkey);
public void brpop(final String[] args);
public void brpoplpush(final String source, final String destination,
final int timeout);
final int timeout);
public void zcount(final String key, final double min, final double max);
public void zcount(final String key, final String min, final String max);
public void zrangeByScore(final String key, final double min,
final double max);
final double max);
public void zrangeByScore(final String key, final String min,
final String max);
final String max);
public void zrangeByScore(final String key, final double min,
final double max, final int offset, int count);
final double max, final int offset, int count);
public void zrangeByScoreWithScores(final String key, final double min,
final double max);
final double max);
public void zrangeByScoreWithScores(final String key, final double min,
final double max, final int offset, final int count);
final double max, final int offset, final int count);
public void zrangeByScoreWithScores(final String key, final String min,
final String max);
final String max);
public void zrangeByScoreWithScores(final String key, final String min,
final String max, final int offset, final int count);
final String max, final int offset, final int count);
public void zrevrangeByScore(final String key, final double max,
final double min);
final double min);
public void zrevrangeByScore(final String key, final String max,
final String min);
final String min);
public void zrevrangeByScore(final String key, final double max,
final double min, final int offset, int count);
final double min, final int offset, int count);
public void zrevrangeByScoreWithScores(final String key, final double max,
final double min);
final double min);
public void zrevrangeByScoreWithScores(final String key, final double max,
final double min, final int offset, final int count);
final double min, final int offset, final int count);
public void zrevrangeByScoreWithScores(final String key, final String max,
final String min);
final String min);
public void zrevrangeByScoreWithScores(final String key, final String max,
final String min, final int offset, final int count);
final String min, final int offset, final int count);
public void zremrangeByRank(final String key, final long start,
final long end);
final long end);
public void zremrangeByScore(final String key, final double start,
final double end);
final double end);
public void zremrangeByScore(final String key, final String start,
final String end);
final String end);
public void zunionstore(final String dstkey, final String... sets);
public void zunionstore(final String dstkey, final ZParams params,
final String... sets);
final String... sets);
public void zinterstore(final String dstkey, final String... sets);
public void zinterstore(final String dstkey, final ZParams params,
final String... sets);
final String... sets);
public void strlen(final String key);
@@ -268,7 +268,7 @@ public interface Commands {
public void echo(final String string);
public void linsert(final String key, final LIST_POSITION where,
final String pivot, final String value);
final String pivot, final String value);
public void bgrewriteaof();
@@ -305,13 +305,13 @@ public interface Commands {
public void scan(final String cursor, final ScanParams params);
public void hscan(final String key, final String cursor,
final ScanParams params);
final ScanParams params);
public void sscan(final String key, final String cursor,
final ScanParams params);
final ScanParams params);
public void zscan(final String key, final String cursor,
final ScanParams params);
final ScanParams params);
public void waitReplicas(int replicas, long timeout);
}

View File

@@ -1,5 +1,12 @@
package redis.clients.jedis;
import redis.clients.jedis.Protocol.Command;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.util.RedisInputStream;
import redis.clients.util.RedisOutputStream;
import redis.clients.util.SafeEncoder;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
@@ -8,13 +15,6 @@ import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import redis.clients.jedis.Protocol.Command;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.util.RedisInputStream;
import redis.clients.util.RedisOutputStream;
import redis.clients.util.SafeEncoder;
public class Connection implements Closeable {
private String host = Protocol.DEFAULT_HOST;
@@ -29,241 +29,239 @@ public class Connection implements Closeable {
}
public Connection(final String host) {
this.host = host;
this.host = host;
}
public Connection(final String host, final int port) {
this.host = host;
this.port = port;
this.host = host;
this.port = port;
}
public Socket getSocket() {
return socket;
return socket;
}
public int getTimeout() {
return timeout;
return timeout;
}
public void setTimeout(final int timeout) {
this.timeout = timeout;
this.timeout = timeout;
}
public void setTimeoutInfinite() {
try {
if (!isConnected()) {
connect();
}
socket.setKeepAlive(true);
socket.setSoTimeout(0);
} catch (SocketException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
try {
if (!isConnected()) {
connect();
}
socket.setSoTimeout(0);
} catch (SocketException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
}
public void rollbackTimeout() {
try {
socket.setSoTimeout(timeout);
socket.setKeepAlive(false);
} catch (SocketException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
try {
socket.setSoTimeout(timeout);
} catch (SocketException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
}
protected Connection sendCommand(final Command cmd, final String... args) {
final byte[][] bargs = new byte[args.length][];
for (int i = 0; i < args.length; i++) {
bargs[i] = SafeEncoder.encode(args[i]);
}
return sendCommand(cmd, bargs);
final byte[][] bargs = new byte[args.length][];
for (int i = 0; i < args.length; i++) {
bargs[i] = SafeEncoder.encode(args[i]);
}
return sendCommand(cmd, bargs);
}
protected Connection sendCommand(final Command cmd, final byte[]... args) {
try {
connect();
Protocol.sendCommand(outputStream, cmd, args);
return this;
} catch (JedisConnectionException ex) {
// Any other exceptions related to connection?
broken = true;
throw ex;
}
try {
connect();
Protocol.sendCommand(outputStream, cmd, args);
return this;
} catch (JedisConnectionException ex) {
// Any other exceptions related to connection?
broken = true;
throw ex;
}
}
protected Connection sendCommand(final Command cmd) {
try {
connect();
Protocol.sendCommand(outputStream, cmd, new byte[0][]);
return this;
} catch (JedisConnectionException ex) {
// Any other exceptions related to connection?
broken = true;
throw ex;
}
try {
connect();
Protocol.sendCommand(outputStream, cmd, new byte[0][]);
return this;
} catch (JedisConnectionException ex) {
// Any other exceptions related to connection?
broken = true;
throw ex;
}
}
public String getHost() {
return host;
return host;
}
public void setHost(final String host) {
this.host = host;
this.host = host;
}
public int getPort() {
return port;
return port;
}
public void setPort(final int port) {
this.port = port;
this.port = port;
}
public void connect() {
if (!isConnected()) {
try {
socket = new Socket();
// ->@wjw_add
socket.setReuseAddress(true);
socket.setKeepAlive(true); // Will monitor the TCP connection is
// valid
socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to
// ensure timely delivery of data
socket.setSoLinger(true, 0); // Control calls close () method,
// the underlying socket is closed
// immediately
// <-@wjw_add
if (!isConnected()) {
try {
socket = new Socket();
// ->@wjw_add
socket.setReuseAddress(true);
socket.setKeepAlive(true); // Will monitor the TCP connection is
// valid
socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to
// ensure timely delivery of data
socket.setSoLinger(true, 0); // Control calls close () method,
// the underlying socket is closed
// immediately
// <-@wjw_add
socket.connect(new InetSocketAddress(host, port), timeout);
socket.setSoTimeout(timeout);
outputStream = new RedisOutputStream(socket.getOutputStream());
inputStream = new RedisInputStream(socket.getInputStream());
} catch (IOException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
}
socket.connect(new InetSocketAddress(host, port), timeout);
socket.setSoTimeout(timeout);
outputStream = new RedisOutputStream(socket.getOutputStream());
inputStream = new RedisInputStream(socket.getInputStream());
} catch (IOException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
}
}
@Override
public void close() {
disconnect();
disconnect();
}
public void disconnect() {
if (isConnected()) {
try {
inputStream.close();
if (!socket.isClosed()) {
outputStream.close();
socket.close();
}
} catch (IOException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
}
if (isConnected()) {
try {
inputStream.close();
if (!socket.isClosed()) {
outputStream.close();
socket.close();
}
} catch (IOException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
}
}
public boolean isConnected() {
return socket != null && socket.isBound() && !socket.isClosed()
&& socket.isConnected() && !socket.isInputShutdown()
&& !socket.isOutputShutdown();
return socket != null && socket.isBound() && !socket.isClosed()
&& socket.isConnected() && !socket.isInputShutdown()
&& !socket.isOutputShutdown();
}
protected String getStatusCodeReply() {
flush();
final byte[] resp = (byte[]) readProtocolWithCheckingBroken();
if (null == resp) {
return null;
} else {
return SafeEncoder.encode(resp);
}
public String getStatusCodeReply() {
flush();
final byte[] resp = (byte[]) readProtocolWithCheckingBroken();
if (null == resp) {
return null;
} else {
return SafeEncoder.encode(resp);
}
}
public String getBulkReply() {
final byte[] result = getBinaryBulkReply();
if (null != result) {
return SafeEncoder.encode(result);
} else {
return null;
}
final byte[] result = getBinaryBulkReply();
if (null != result) {
return SafeEncoder.encode(result);
} else {
return null;
}
}
public byte[] getBinaryBulkReply() {
flush();
return (byte[]) readProtocolWithCheckingBroken();
flush();
return (byte[]) readProtocolWithCheckingBroken();
}
public Long getIntegerReply() {
flush();
return (Long) readProtocolWithCheckingBroken();
flush();
return (Long) readProtocolWithCheckingBroken();
}
public List<String> getMultiBulkReply() {
return BuilderFactory.STRING_LIST.build(getBinaryMultiBulkReply());
return BuilderFactory.STRING_LIST.build(getBinaryMultiBulkReply());
}
@SuppressWarnings("unchecked")
public List<byte[]> getBinaryMultiBulkReply() {
flush();
return (List<byte[]>) readProtocolWithCheckingBroken();
flush();
return (List<byte[]>) readProtocolWithCheckingBroken();
}
@SuppressWarnings("unchecked")
public List<Object> getRawObjectMultiBulkReply() {
return (List<Object>) readProtocolWithCheckingBroken();
return (List<Object>) readProtocolWithCheckingBroken();
}
public List<Object> getObjectMultiBulkReply() {
flush();
return getRawObjectMultiBulkReply();
flush();
return getRawObjectMultiBulkReply();
}
@SuppressWarnings("unchecked")
public List<Long> getIntegerMultiBulkReply() {
flush();
return (List<Long>) Protocol.read(inputStream);
flush();
return (List<Long>) Protocol.read(inputStream);
}
public Object getOne() {
flush();
return readProtocolWithCheckingBroken();
flush();
return readProtocolWithCheckingBroken();
}
public boolean isBroken() {
return broken;
return broken;
}
protected void flush() {
try {
outputStream.flush();
} catch (IOException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
try {
outputStream.flush();
} catch (IOException ex) {
broken = true;
throw new JedisConnectionException(ex);
}
}
protected Object readProtocolWithCheckingBroken() {
try {
return Protocol.read(inputStream);
} catch (JedisConnectionException exc) {
broken = true;
throw exc;
}
try {
return Protocol.read(inputStream);
} catch (JedisConnectionException exc) {
broken = true;
throw exc;
}
}
public List<Object> getMany(int count) {
flush();
List<Object> responses = new ArrayList<Object>();
for (int i = 0; i < count; i++) {
try {
responses.add(readProtocolWithCheckingBroken());
} catch (JedisDataException e) {
responses.add(e);
}
}
return responses;
public List<Object> getMany(final int count) {
flush();
final List<Object> responses = new ArrayList<Object>(count);
for (int i = 0; i < count; i++) {
try {
responses.add(readProtocolWithCheckingBroken());
} catch (JedisDataException e) {
responses.add(e);
}
}
return responses;
}
}

View File

@@ -4,7 +4,7 @@ public class DebugParams {
private String[] command;
public String[] getCommand() {
return command;
return command;
}
private DebugParams() {
@@ -12,20 +12,20 @@ public class DebugParams {
}
public static DebugParams SEGFAULT() {
DebugParams debugParams = new DebugParams();
debugParams.command = new String[] { "SEGFAULT" };
return debugParams;
DebugParams debugParams = new DebugParams();
debugParams.command = new String[] { "SEGFAULT" };
return debugParams;
}
public static DebugParams OBJECT(String key) {
DebugParams debugParams = new DebugParams();
debugParams.command = new String[] { "OBJECT", key };
return debugParams;
DebugParams debugParams = new DebugParams();
debugParams.command = new String[] { "OBJECT", key };
return debugParams;
}
public static DebugParams RELOAD() {
DebugParams debugParams = new DebugParams();
debugParams.command = new String[] { "RELOAD" };
return debugParams;
DebugParams debugParams = new DebugParams();
debugParams.command = new String[] { "RELOAD" };
return debugParams;
}
}

View File

@@ -7,48 +7,48 @@ public class HostAndPort {
private int port;
public HostAndPort(String host, int port) {
this.host = host;
this.port = port;
this.host = host;
this.port = port;
}
public String getHost() {
return host;
return host;
}
public int getPort() {
return port;
return port;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof HostAndPort) {
HostAndPort hp = (HostAndPort) obj;
if (obj instanceof HostAndPort) {
HostAndPort hp = (HostAndPort) obj;
String thisHost = convertHost(host);
String hpHost = convertHost(hp.host);
return port == hp.port && thisHost.equals(hpHost);
String thisHost = convertHost(host);
String hpHost = convertHost(hp.host);
return port == hp.port && thisHost.equals(hpHost);
}
}
return false;
return false;
}
@Override
public int hashCode() {
return 31 * convertHost(host).hashCode() + port;
return 31 * convertHost(host).hashCode() + port;
}
@Override
public String toString() {
return host + ":" + port;
return host + ":" + port;
}
private String convertHost(String host) {
if (host.equals("127.0.0.1"))
return LOCALHOST_STR;
else if (host.equals("::1"))
return LOCALHOST_STR;
if (host.equals("127.0.0.1"))
return LOCALHOST_STR;
else if (host.equals("::1"))
return LOCALHOST_STR;
return host;
return host;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -16,94 +16,94 @@ public abstract class JedisClusterCommand<T> {
private ThreadLocal<Jedis> askConnection = new ThreadLocal<Jedis>();
public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler,
int timeout, int maxRedirections) {
this.connectionHandler = connectionHandler;
this.commandTimeout = timeout;
this.redirections = maxRedirections;
int timeout, int maxRedirections) {
this.connectionHandler = connectionHandler;
this.commandTimeout = timeout;
this.redirections = maxRedirections;
}
public abstract T execute(Jedis connection);
public T run(String key) {
if (key == null) {
throw new JedisClusterException(
"No way to dispatch this command to Redis Cluster.");
}
if (key == null) {
throw new JedisClusterException(
"No way to dispatch this command to Redis Cluster.");
}
return runWithRetries(key, this.redirections, false, false);
return runWithRetries(key, this.redirections, false, false);
}
private T runWithRetries(String key, int redirections,
boolean tryRandomNode, boolean asking) {
if (redirections <= 0) {
throw new JedisClusterMaxRedirectionsException(
"Too many Cluster redirections?");
}
boolean tryRandomNode, boolean asking) {
if (redirections <= 0) {
throw new JedisClusterMaxRedirectionsException(
"Too many Cluster redirections?");
}
Jedis connection = null;
try {
Jedis connection = null;
try {
if (asking) {
// TODO: Pipeline asking with the original command to make it
// faster....
connection = askConnection.get();
connection.asking();
if (asking) {
// TODO: Pipeline asking with the original command to make it
// faster....
connection = askConnection.get();
connection.asking();
// if asking success, reset asking flag
asking = false;
} else {
if (tryRandomNode) {
connection = connectionHandler.getConnection();
} else {
connection = connectionHandler
.getConnectionFromSlot(JedisClusterCRC16
.getSlot(key));
}
}
// if asking success, reset asking flag
asking = false;
} else {
if (tryRandomNode) {
connection = connectionHandler.getConnection();
} else {
connection = connectionHandler
.getConnectionFromSlot(JedisClusterCRC16
.getSlot(key));
}
}
return execute(connection);
} catch (JedisConnectionException jce) {
if (tryRandomNode) {
// maybe all connection is down
throw jce;
}
return execute(connection);
} catch (JedisConnectionException jce) {
if (tryRandomNode) {
// maybe all connection is down
throw jce;
}
releaseConnection(connection, true);
connection = null;
releaseConnection(connection, true);
connection = null;
// retry with random connection
return runWithRetries(key, redirections - 1, true, asking);
} catch (JedisRedirectionException jre) {
if (jre instanceof JedisAskDataException) {
asking = true;
askConnection.set(this.connectionHandler
.getConnectionFromNode(jre.getTargetNode()));
} else if (jre instanceof JedisMovedDataException) {
// it rebuilds cluster's slot cache
// recommended by Redis cluster specification
this.connectionHandler.renewSlotCache();
} else {
throw new JedisClusterException(jre);
}
// retry with random connection
return runWithRetries(key, redirections - 1, true, asking);
} catch (JedisRedirectionException jre) {
if (jre instanceof JedisAskDataException) {
asking = true;
askConnection.set(this.connectionHandler
.getConnectionFromNode(jre.getTargetNode()));
} else if (jre instanceof JedisMovedDataException) {
// it rebuilds cluster's slot cache
// recommended by Redis cluster specification
this.connectionHandler.renewSlotCache();
} else {
throw new JedisClusterException(jre);
}
releaseConnection(connection, false);
connection = null;
releaseConnection(connection, false);
connection = null;
return runWithRetries(key, redirections - 1, false, asking);
} finally {
releaseConnection(connection, false);
}
return runWithRetries(key, redirections - 1, false, asking);
} finally {
releaseConnection(connection, false);
}
}
private void releaseConnection(Jedis connection, boolean broken) {
if (connection != null) {
if (broken) {
connectionHandler.returnBrokenConnection(connection);
} else {
connectionHandler.returnConnection(connection);
}
}
if (connection != null) {
if (broken) {
connectionHandler.returnBrokenConnection(connection);
} else {
connectionHandler.returnConnection(connection);
}
}
}
}

View File

@@ -15,75 +15,75 @@ public abstract class JedisClusterConnectionHandler {
abstract Jedis getConnection();
public void returnConnection(Jedis connection) {
cache.getNode(getNodeKey(connection.getClient())).returnResource(
connection);
cache.getNode(getNodeKey(connection.getClient())).returnResource(
connection);
}
public void returnBrokenConnection(Jedis connection) {
cache.getNode(getNodeKey(connection.getClient())).returnBrokenResource(
connection);
cache.getNode(getNodeKey(connection.getClient())).returnBrokenResource(
connection);
}
abstract Jedis getConnectionFromSlot(int slot);
public Jedis getConnectionFromNode(HostAndPort node) {
cache.setNodeIfNotExist(node);
return cache.getNode(JedisClusterInfoCache.getNodeKey(node))
.getResource();
cache.setNodeIfNotExist(node);
return cache.getNode(JedisClusterInfoCache.getNodeKey(node))
.getResource();
}
public JedisClusterConnectionHandler(Set<HostAndPort> nodes,
final GenericObjectPoolConfig poolConfig) {
this.cache = new JedisClusterInfoCache(poolConfig);
initializeSlotsCache(nodes, poolConfig);
final GenericObjectPoolConfig poolConfig) {
this.cache = new JedisClusterInfoCache(poolConfig);
initializeSlotsCache(nodes, poolConfig);
}
public Map<String, JedisPool> getNodes() {
return cache.getNodes();
return cache.getNodes();
}
public void assignSlotToNode(int slot, HostAndPort targetNode) {
cache.assignSlotToNode(slot, targetNode);
cache.assignSlotToNode(slot, targetNode);
}
private void initializeSlotsCache(Set<HostAndPort> startNodes,
GenericObjectPoolConfig poolConfig) {
for (HostAndPort hostAndPort : startNodes) {
JedisPool jp = new JedisPool(poolConfig, hostAndPort.getHost(),
hostAndPort.getPort());
GenericObjectPoolConfig poolConfig) {
for (HostAndPort hostAndPort : startNodes) {
JedisPool jp = new JedisPool(poolConfig, hostAndPort.getHost(),
hostAndPort.getPort());
Jedis jedis = null;
try {
jedis = jp.getResource();
cache.discoverClusterNodesAndSlots(jedis);
break;
} catch (JedisConnectionException e) {
// try next nodes
} finally {
if (jedis != null) {
jedis.close();
}
}
}
Jedis jedis = null;
try {
jedis = jp.getResource();
cache.discoverClusterNodesAndSlots(jedis);
break;
} catch (JedisConnectionException e) {
// try next nodes
} finally {
if (jedis != null) {
jedis.close();
}
}
}
for (HostAndPort node : startNodes) {
cache.setNodeIfNotExist(node);
}
for (HostAndPort node : startNodes) {
cache.setNodeIfNotExist(node);
}
}
public void renewSlotCache() {
for (JedisPool jp : cache.getNodes().values()) {
Jedis jedis = null;
try {
jedis = jp.getResource();
cache.discoverClusterSlots(jedis);
break;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
for (JedisPool jp : cache.getNodes().values()) {
Jedis jedis = null;
try {
jedis = jp.getResource();
cache.discoverClusterSlots(jedis);
break;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}
}

View File

@@ -25,166 +25,166 @@ public class JedisClusterInfoCache {
private final GenericObjectPoolConfig poolConfig;
public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig) {
this.poolConfig = poolConfig;
this.poolConfig = poolConfig;
}
public void discoverClusterNodesAndSlots(Jedis jedis) {
w.lock();
w.lock();
try {
this.nodes.clear();
this.slots.clear();
try {
this.nodes.clear();
this.slots.clear();
String localNodes = jedis.clusterNodes();
for (String nodeInfo : localNodes.split("\n")) {
ClusterNodeInformation clusterNodeInfo = nodeInfoParser.parse(
nodeInfo, new HostAndPort(jedis.getClient().getHost(),
jedis.getClient().getPort()));
String localNodes = jedis.clusterNodes();
for (String nodeInfo : localNodes.split("\n")) {
ClusterNodeInformation clusterNodeInfo = nodeInfoParser.parse(
nodeInfo, new HostAndPort(jedis.getClient().getHost(),
jedis.getClient().getPort()));
HostAndPort targetNode = clusterNodeInfo.getNode();
setNodeIfNotExist(targetNode);
assignSlotsToNode(clusterNodeInfo.getAvailableSlots(),
targetNode);
}
} finally {
w.unlock();
}
HostAndPort targetNode = clusterNodeInfo.getNode();
setNodeIfNotExist(targetNode);
assignSlotsToNode(clusterNodeInfo.getAvailableSlots(),
targetNode);
}
} finally {
w.unlock();
}
}
public void discoverClusterSlots(Jedis jedis) {
w.lock();
w.lock();
try {
this.slots.clear();
try {
this.slots.clear();
List<Object> slots = jedis.clusterSlots();
List<Object> slots = jedis.clusterSlots();
for (Object slotInfoObj : slots) {
List<Object> slotInfo = (List<Object>) slotInfoObj;
for (Object slotInfoObj : slots) {
List<Object> slotInfo = (List<Object>) slotInfoObj;
if (slotInfo.size() <= 2) {
continue;
}
if (slotInfo.size() <= 2) {
continue;
}
List<Integer> slotNums = getAssignedSlotArray(slotInfo);
List<Integer> slotNums = getAssignedSlotArray(slotInfo);
// hostInfos
List<Object> hostInfos = (List<Object>) slotInfo.get(2);
if (hostInfos.size() <= 0) {
continue;
}
// hostInfos
List<Object> hostInfos = (List<Object>) slotInfo.get(2);
if (hostInfos.size() <= 0) {
continue;
}
// at this time, we just use master, discard slave information
HostAndPort targetNode = generateHostAndPort(hostInfos);
// at this time, we just use master, discard slave information
HostAndPort targetNode = generateHostAndPort(hostInfos);
setNodeIfNotExist(targetNode);
assignSlotsToNode(slotNums, targetNode);
}
} finally {
w.unlock();
}
setNodeIfNotExist(targetNode);
assignSlotsToNode(slotNums, targetNode);
}
} finally {
w.unlock();
}
}
private HostAndPort generateHostAndPort(List<Object> hostInfos) {
return new HostAndPort(SafeEncoder.encode((byte[]) hostInfos.get(0)),
((Long) hostInfos.get(1)).intValue());
return new HostAndPort(SafeEncoder.encode((byte[]) hostInfos.get(0)),
((Long) hostInfos.get(1)).intValue());
}
public void setNodeIfNotExist(HostAndPort node) {
w.lock();
try {
String nodeKey = getNodeKey(node);
if (nodes.containsKey(nodeKey))
return;
w.lock();
try {
String nodeKey = getNodeKey(node);
if (nodes.containsKey(nodeKey))
return;
JedisPool nodePool = new JedisPool(poolConfig, node.getHost(),
node.getPort());
nodes.put(nodeKey, nodePool);
} finally {
w.unlock();
}
JedisPool nodePool = new JedisPool(poolConfig, node.getHost(),
node.getPort());
nodes.put(nodeKey, nodePool);
} finally {
w.unlock();
}
}
public void assignSlotToNode(int slot, HostAndPort targetNode) {
w.lock();
try {
JedisPool targetPool = nodes.get(getNodeKey(targetNode));
w.lock();
try {
JedisPool targetPool = nodes.get(getNodeKey(targetNode));
if (targetPool == null) {
setNodeIfNotExist(targetNode);
targetPool = nodes.get(getNodeKey(targetNode));
}
slots.put(slot, targetPool);
} finally {
w.unlock();
}
if (targetPool == null) {
setNodeIfNotExist(targetNode);
targetPool = nodes.get(getNodeKey(targetNode));
}
slots.put(slot, targetPool);
} finally {
w.unlock();
}
}
public void assignSlotsToNode(List<Integer> targetSlots,
HostAndPort targetNode) {
w.lock();
try {
JedisPool targetPool = nodes.get(getNodeKey(targetNode));
HostAndPort targetNode) {
w.lock();
try {
JedisPool targetPool = nodes.get(getNodeKey(targetNode));
if (targetPool == null) {
setNodeIfNotExist(targetNode);
targetPool = nodes.get(getNodeKey(targetNode));
}
if (targetPool == null) {
setNodeIfNotExist(targetNode);
targetPool = nodes.get(getNodeKey(targetNode));
}
for (Integer slot : targetSlots) {
slots.put(slot, targetPool);
}
} finally {
w.unlock();
}
for (Integer slot : targetSlots) {
slots.put(slot, targetPool);
}
} finally {
w.unlock();
}
}
public JedisPool getNode(String nodeKey) {
r.lock();
try {
return nodes.get(nodeKey);
} finally {
r.unlock();
}
r.lock();
try {
return nodes.get(nodeKey);
} finally {
r.unlock();
}
}
public JedisPool getSlotPool(int slot) {
r.lock();
try {
return slots.get(slot);
} finally {
r.unlock();
}
r.lock();
try {
return slots.get(slot);
} finally {
r.unlock();
}
}
public Map<String, JedisPool> getNodes() {
r.lock();
try {
return new HashMap<String, JedisPool>(nodes);
} finally {
r.unlock();
}
r.lock();
try {
return new HashMap<String, JedisPool>(nodes);
} finally {
r.unlock();
}
}
public static String getNodeKey(HostAndPort hnp) {
return hnp.getHost() + ":" + hnp.getPort();
return hnp.getHost() + ":" + hnp.getPort();
}
public static String getNodeKey(Client client) {
return client.getHost() + ":" + client.getPort();
return client.getHost() + ":" + client.getPort();
}
public static String getNodeKey(Jedis jedis) {
return getNodeKey(jedis.getClient());
return getNodeKey(jedis.getClient());
}
private List<Integer> getAssignedSlotArray(List<Object> slotInfo) {
List<Integer> slotNums = new ArrayList<Integer>();
for (int slot = ((Long) slotInfo.get(0)).intValue(); slot <= ((Long) slotInfo
.get(1)).intValue(); slot++) {
slotNums.add(slot);
}
return slotNums;
List<Integer> slotNums = new ArrayList<Integer>();
for (int slot = ((Long) slotInfo.get(0)).intValue(); slot <= ((Long) slotInfo
.get(1)).intValue(); slot++) {
slotNums.add(slot);
}
return slotNums;
}
}

View File

@@ -48,6 +48,8 @@ public interface JedisCommands {
Long incrBy(String key, long integer);
Double incrByFloat(String key, double value);
Long incr(String key);
Long append(String key, String value);
@@ -155,38 +157,38 @@ public interface JedisCommands {
Set<String> zrevrangeByScore(String key, double max, double min);
Set<String> zrangeByScore(String key, double min, double max, int offset,
int count);
int count);
Set<String> zrevrangeByScore(String key, String max, String min);
Set<String> zrangeByScore(String key, String min, String max, int offset,
int count);
int count);
Set<String> zrevrangeByScore(String key, double max, double min,
int offset, int count);
int offset, int count);
Set<Tuple> zrangeByScoreWithScores(String key, double min, double max);
Set<Tuple> zrevrangeByScoreWithScores(String key, double max, double min);
Set<Tuple> zrangeByScoreWithScores(String key, double min, double max,
int offset, int count);
int offset, int count);
Set<String> zrevrangeByScore(String key, String max, String min,
int offset, int count);
int offset, int count);
Set<Tuple> zrangeByScoreWithScores(String key, String min, String max);
Set<Tuple> zrevrangeByScoreWithScores(String key, String max, String min);
Set<Tuple> zrangeByScoreWithScores(String key, String min, String max,
int offset, int count);
int offset, int count);
Set<Tuple> zrevrangeByScoreWithScores(String key, double max, double min,
int offset, int count);
int offset, int count);
Set<Tuple> zrevrangeByScoreWithScores(String key, String max, String min,
int offset, int count);
int offset, int count);
Long zremrangeByRank(String key, long start, long end);
@@ -199,27 +201,35 @@ public interface JedisCommands {
Set<String> zrangeByLex(final String key, final String min, final String max);
Set<String> zrangeByLex(final String key, final String min,
final String max, final int offset, final int count);
final String max, final int offset, final int count);
Set<String> zrevrangeByLex(final String key, final String max,
final String min);
final String min);
Set<String> zrevrangeByLex(final String key, final String max,
final String min, final int offset, final int count);
final String min, final int offset, final int count);
Long zremrangeByLex(final String key, final String min, final String max);
Long linsert(String key, Client.LIST_POSITION where, String pivot,
String value);
String value);
Long lpushx(String key, String... string);
Long rpushx(String key, String... string);
/**
* @deprecated unusable command, this will be removed in 3.0.0.
*/
@Deprecated
List<String> blpop(String arg);
List<String> blpop(int timeout, String key);
/**
* @deprecated unusable command, this will be removed in 3.0.0.
*/
@Deprecated
List<String> brpop(String arg);
List<String> brpop(int timeout, String key);
@@ -235,7 +245,7 @@ public interface JedisCommands {
Long bitcount(final String key, long start, long end);
ScanResult<Map.Entry<String, String>> hscan(final String key,
final String cursor);
final String cursor);
ScanResult<String> sscan(final String key, final String cursor);

View File

@@ -17,91 +17,91 @@ class JedisFactory implements PooledObjectFactory<Jedis> {
private final String clientName;
public JedisFactory(final String host, final int port, final int timeout,
final String password, final int database) {
this(host, port, timeout, password, database, null);
final String password, final int database) {
this(host, port, timeout, password, database, null);
}
public JedisFactory(final String host, final int port, final int timeout,
final String password, final int database, final String clientName) {
super();
this.hostAndPort.set(new HostAndPort(host, port));
this.timeout = timeout;
this.password = password;
this.database = database;
this.clientName = clientName;
final String password, final int database, final String clientName) {
super();
this.hostAndPort.set(new HostAndPort(host, port));
this.timeout = timeout;
this.password = password;
this.database = database;
this.clientName = clientName;
}
public void setHostAndPort(final HostAndPort hostAndPort) {
this.hostAndPort.set(hostAndPort);
this.hostAndPort.set(hostAndPort);
}
@Override
public void activateObject(PooledObject<Jedis> pooledJedis)
throws Exception {
final BinaryJedis jedis = pooledJedis.getObject();
if (jedis.getDB() != database) {
jedis.select(database);
}
throws Exception {
final BinaryJedis jedis = pooledJedis.getObject();
if (jedis.getDB() != database) {
jedis.select(database);
}
}
@Override
public void destroyObject(PooledObject<Jedis> pooledJedis) throws Exception {
final BinaryJedis jedis = pooledJedis.getObject();
if (jedis.isConnected()) {
try {
try {
jedis.quit();
} catch (Exception e) {
}
jedis.disconnect();
} catch (Exception e) {
final BinaryJedis jedis = pooledJedis.getObject();
if (jedis.isConnected()) {
try {
try {
jedis.quit();
} catch (Exception e) {
}
jedis.disconnect();
} catch (Exception e) {
}
}
}
}
}
@Override
public PooledObject<Jedis> makeObject() throws Exception {
final HostAndPort hostAndPort = this.hostAndPort.get();
final Jedis jedis = new Jedis(hostAndPort.getHost(),
hostAndPort.getPort(), this.timeout);
final HostAndPort hostAndPort = this.hostAndPort.get();
final Jedis jedis = new Jedis(hostAndPort.getHost(),
hostAndPort.getPort(), this.timeout);
jedis.connect();
if (null != this.password) {
jedis.auth(this.password);
}
if (database != 0) {
jedis.select(database);
}
if (clientName != null) {
jedis.clientSetname(clientName);
}
jedis.connect();
if (null != this.password) {
jedis.auth(this.password);
}
if (database != 0) {
jedis.select(database);
}
if (clientName != null) {
jedis.clientSetname(clientName);
}
return new DefaultPooledObject<Jedis>(jedis);
return new DefaultPooledObject<Jedis>(jedis);
}
@Override
public void passivateObject(PooledObject<Jedis> pooledJedis)
throws Exception {
// TODO maybe should select db 0? Not sure right now.
throws Exception {
// TODO maybe should select db 0? Not sure right now.
}
@Override
public boolean validateObject(PooledObject<Jedis> pooledJedis) {
final BinaryJedis jedis = pooledJedis.getObject();
try {
HostAndPort hostAndPort = this.hostAndPort.get();
final BinaryJedis jedis = pooledJedis.getObject();
try {
HostAndPort hostAndPort = this.hostAndPort.get();
String connectionHost = jedis.getClient().getHost();
int connectionPort = jedis.getClient().getPort();
String connectionHost = jedis.getClient().getHost();
int connectionPort = jedis.getClient().getPort();
return hostAndPort.getHost().equals(connectionHost)
&& hostAndPort.getPort() == connectionPort
&& jedis.isConnected() && jedis.ping().equals("PONG");
} catch (final Exception e) {
return false;
}
return hostAndPort.getHost().equals(connectionHost)
&& hostAndPort.getPort() == connectionPort
&& jedis.isConnected() && jedis.ping().equals("PONG");
} catch (final Exception e) {
return false;
}
}
}

View File

@@ -4,12 +4,12 @@ public abstract class JedisMonitor {
protected Client client;
public void proceed(Client client) {
this.client = client;
this.client.setTimeoutInfinite();
do {
String command = client.getBulkReply();
onCommand(command);
} while (client.isConnected());
this.client = client;
this.client.setTimeoutInfinite();
do {
String command = client.getBulkReply();
onCommand(command);
} while (client.isConnected());
}
public abstract void onCommand(String command);

View File

@@ -5,124 +5,132 @@ import java.net.URI;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.util.JedisURIHelper;
import redis.clients.util.Pool;
public class JedisPool extends Pool<Jedis> {
public JedisPool() {
this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT);
this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) {
this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
null, Protocol.DEFAULT_DATABASE, null);
this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
null, Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(String host, int port) {
this(new GenericObjectPoolConfig(), host, port,
Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null);
this(new GenericObjectPoolConfig(), host, port,
Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(final String host) {
URI uri = URI.create(host);
if (uri.getScheme() != null && uri.getScheme().equals("redis")) {
String h = uri.getHost();
int port = uri.getPort();
String password = JedisURIHelper.getPassword(uri);
int database = 0;
Integer dbIndex = JedisURIHelper.getDBIndex(uri);
if (dbIndex != null) {
database = dbIndex.intValue();
}
this.internalPool = new GenericObjectPool<Jedis>(
new JedisFactory(h, port, Protocol.DEFAULT_TIMEOUT,
password, database, null),
new GenericObjectPoolConfig());
} else {
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(
host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
null, Protocol.DEFAULT_DATABASE, null),
new GenericObjectPoolConfig());
}
URI uri = URI.create(host);
if (uri.getScheme() != null && uri.getScheme().equals("redis")) {
String h = uri.getHost();
int port = uri.getPort();
String password = JedisURIHelper.getPassword(uri);
int database = 0;
Integer dbIndex = JedisURIHelper.getDBIndex(uri);
if (dbIndex != null) {
database = dbIndex.intValue();
}
this.internalPool = new GenericObjectPool<Jedis>(
new JedisFactory(h, port, Protocol.DEFAULT_TIMEOUT,
password, database, null),
new GenericObjectPoolConfig());
} else {
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(
host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
null, Protocol.DEFAULT_DATABASE, null),
new GenericObjectPoolConfig());
}
}
public JedisPool(final URI uri) {
this(new GenericObjectPoolConfig(), uri, Protocol.DEFAULT_TIMEOUT);
this(new GenericObjectPoolConfig(), uri, Protocol.DEFAULT_TIMEOUT);
}
public JedisPool(final URI uri, final int timeout) {
this(new GenericObjectPoolConfig(), uri, timeout);
this(new GenericObjectPoolConfig(), uri, timeout);
}
public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, int port, int timeout, final String password) {
this(poolConfig, host, port, timeout, password,
Protocol.DEFAULT_DATABASE, null);
final String host, int port, int timeout, final String password) {
this(poolConfig, host, port, timeout, password,
Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, final int port) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null);
final String host, final int port) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, final int port, final int timeout) {
this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE,
null);
final String host, final int port, final int timeout) {
this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE,
null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, int port, int timeout, final String password,
final int database) {
this(poolConfig, host, port, timeout, password, database, null);
final String host, int port, int timeout, final String password,
final int database) {
this(poolConfig, host, port, timeout, password, database, null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, int port, int timeout, final String password,
final int database, final String clientName) {
super(poolConfig, new JedisFactory(host, port, timeout, password,
database, clientName));
final String host, int port, int timeout, final String password,
final int database, final String clientName) {
super(poolConfig, new JedisFactory(host, port, timeout, password,
database, clientName));
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri) {
this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT);
this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri,
final int timeout) {
super(poolConfig, new JedisFactory(uri.getHost(), uri.getPort(),
timeout, JedisURIHelper.getPassword(uri),
JedisURIHelper.getDBIndex(uri) != null ? JedisURIHelper
.getDBIndex(uri) : 0, null));
final int timeout) {
super(poolConfig, new JedisFactory(uri.getHost(), uri.getPort(),
timeout, JedisURIHelper.getPassword(uri),
JedisURIHelper.getDBIndex(uri) != null ? JedisURIHelper
.getDBIndex(uri) : 0, null));
}
@Override
public Jedis getResource() {
Jedis jedis = super.getResource();
jedis.setDataSource(this);
return jedis;
Jedis jedis = super.getResource();
jedis.setDataSource(this);
return jedis;
}
public void returnBrokenResource(final Jedis resource) {
if (resource != null) {
returnBrokenResourceObject(resource);
}
if (resource != null) {
returnBrokenResourceObject(resource);
}
}
public void returnResource(final Jedis resource) {
if (resource != null) {
resource.resetState();
returnResourceObject(resource);
}
if (resource != null) {
try {
resource.resetState();
returnResourceObject(resource);
}
catch (Exception e) {
returnBrokenResource(resource);
throw new JedisException(
"Could not return the resource to the pool", e);
}
}
}
public int getNumActive() {
if (this.internalPool == null || this.internalPool.isClosed()) {
return -1;
}
if (this.internalPool == null || this.internalPool.isClosed()) {
return -1;
}
return this.internalPool.getNumActive();
return this.internalPool.getNumActive();
}
}

View File

@@ -4,10 +4,10 @@ import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
public class JedisPoolConfig extends GenericObjectPoolConfig {
public JedisPoolConfig() {
// defaults to make your life with connection pool easier :)
setTestWhileIdle(true);
setMinEvictableIdleTimeMillis(60000);
setTimeBetweenEvictionRunsMillis(30000);
setNumTestsPerEvictionRun(-1);
// defaults to make your life with connection pool easier :)
setTestWhileIdle(true);
setMinEvictableIdleTimeMillis(60000);
setTimeBetweenEvictionRunsMillis(30000);
setNumTestsPerEvictionRun(-1);
}
}

View File

@@ -18,153 +18,152 @@ public abstract class JedisPubSub {
private int subscribedChannels = 0;
private volatile Client client;
public abstract void onMessage(String channel, String message);
public void onMessage(String channel, String message) {}
public abstract void onPMessage(String pattern, String channel,
String message);
public void onPMessage(String pattern, String channel, String message) {}
public abstract void onSubscribe(String channel, int subscribedChannels);
public void onSubscribe(String channel, int subscribedChannels) {}
public abstract void onUnsubscribe(String channel, int subscribedChannels);
public void onUnsubscribe(String channel, int subscribedChannels) {}
public abstract void onPUnsubscribe(String pattern, int subscribedChannels);
public void onPUnsubscribe(String pattern, int subscribedChannels) {}
public abstract void onPSubscribe(String pattern, int subscribedChannels);
public void onPSubscribe(String pattern, int subscribedChannels) {}
public void unsubscribe() {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub was not subscribed to a Jedis instance.");
}
client.unsubscribe();
client.flush();
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub was not subscribed to a Jedis instance.");
}
client.unsubscribe();
client.flush();
}
public void unsubscribe(String... channels) {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.unsubscribe(channels);
client.flush();
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.unsubscribe(channels);
client.flush();
}
public void subscribe(String... channels) {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.subscribe(channels);
client.flush();
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.subscribe(channels);
client.flush();
}
public void psubscribe(String... patterns) {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.psubscribe(patterns);
client.flush();
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.psubscribe(patterns);
client.flush();
}
public void punsubscribe() {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.punsubscribe();
client.flush();
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.punsubscribe();
client.flush();
}
public void punsubscribe(String... patterns) {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.punsubscribe(patterns);
client.flush();
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.punsubscribe(patterns);
client.flush();
}
public boolean isSubscribed() {
return subscribedChannels > 0;
return subscribedChannels > 0;
}
public void proceedWithPatterns(Client client, String... patterns) {
this.client = client;
client.psubscribe(patterns);
client.flush();
process(client);
this.client = client;
client.psubscribe(patterns);
client.flush();
process(client);
}
public void proceed(Client client, String... channels) {
this.client = client;
client.subscribe(channels);
client.flush();
process(client);
this.client = client;
client.subscribe(channels);
client.flush();
process(client);
}
private void process(Client client) {
do {
List<Object> reply = client.getRawObjectMultiBulkReply();
final Object firstObj = reply.get(0);
if (!(firstObj instanceof byte[])) {
throw new JedisException("Unknown message type: " + firstObj);
}
final byte[] resp = (byte[]) firstObj;
if (Arrays.equals(SUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
onSubscribe(strchannel, subscribedChannels);
} else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
onUnsubscribe(strchannel, subscribedChannels);
} else if (Arrays.equals(MESSAGE.raw, resp)) {
final byte[] bchannel = (byte[]) reply.get(1);
final byte[] bmesg = (byte[]) reply.get(2);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
final String strmesg = (bmesg == null) ? null : SafeEncoder
.encode(bmesg);
onMessage(strchannel, strmesg);
} else if (Arrays.equals(PMESSAGE.raw, resp)) {
final byte[] bpattern = (byte[]) reply.get(1);
final byte[] bchannel = (byte[]) reply.get(2);
final byte[] bmesg = (byte[]) reply.get(3);
final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
final String strmesg = (bmesg == null) ? null : SafeEncoder
.encode(bmesg);
onPMessage(strpattern, strchannel, strmesg);
} else if (Arrays.equals(PSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1);
final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern);
onPSubscribe(strpattern, subscribedChannels);
} else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1);
final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern);
onPUnsubscribe(strpattern, subscribedChannels);
} else {
throw new JedisException("Unknown message type: " + firstObj);
}
} while (isSubscribed());
do {
List<Object> reply = client.getRawObjectMultiBulkReply();
final Object firstObj = reply.get(0);
if (!(firstObj instanceof byte[])) {
throw new JedisException("Unknown message type: " + firstObj);
}
final byte[] resp = (byte[]) firstObj;
if (Arrays.equals(SUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
onSubscribe(strchannel, subscribedChannels);
} else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
onUnsubscribe(strchannel, subscribedChannels);
} else if (Arrays.equals(MESSAGE.raw, resp)) {
final byte[] bchannel = (byte[]) reply.get(1);
final byte[] bmesg = (byte[]) reply.get(2);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
final String strmesg = (bmesg == null) ? null : SafeEncoder
.encode(bmesg);
onMessage(strchannel, strmesg);
} else if (Arrays.equals(PMESSAGE.raw, resp)) {
final byte[] bpattern = (byte[]) reply.get(1);
final byte[] bchannel = (byte[]) reply.get(2);
final byte[] bmesg = (byte[]) reply.get(3);
final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
final String strmesg = (bmesg == null) ? null : SafeEncoder
.encode(bmesg);
onPMessage(strpattern, strchannel, strmesg);
} else if (Arrays.equals(PSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1);
final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern);
onPSubscribe(strpattern, subscribedChannels);
} else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1);
final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern);
onPUnsubscribe(strpattern, subscribedChannels);
} else {
throw new JedisException("Unknown message type: " + firstObj);
}
} while (isSubscribed());
/* Invalidate instance since this thread is no longer listening */
this.client = null;
/* Invalidate instance since this thread is no longer listening */
this.client = null;
}
public int getSubscribedChannels() {
return subscribedChannels;
return subscribedChannels;
}
}

View File

@@ -28,320 +28,294 @@ public class JedisSentinelPool extends Pool<Jedis> {
protected Logger log = Logger.getLogger(getClass().getName());
public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE);
final GenericObjectPoolConfig poolConfig) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE);
}
public JedisSentinelPool(String masterName, Set<String> sentinels) {
this(masterName, sentinels, new GenericObjectPoolConfig(),
Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE);
this(masterName, sentinels, new GenericObjectPoolConfig(),
Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE);
}
public JedisSentinelPool(String masterName, Set<String> sentinels,
String password) {
this(masterName, sentinels, new GenericObjectPoolConfig(),
Protocol.DEFAULT_TIMEOUT, password);
String password) {
this(masterName, sentinels, new GenericObjectPoolConfig(),
Protocol.DEFAULT_TIMEOUT, password);
}
public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, int timeout,
final String password) {
this(masterName, sentinels, poolConfig, timeout, password,
Protocol.DEFAULT_DATABASE);
final GenericObjectPoolConfig poolConfig, int timeout,
final String password) {
this(masterName, sentinels, poolConfig, timeout, password,
Protocol.DEFAULT_DATABASE);
}
public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, final int timeout) {
this(masterName, sentinels, poolConfig, timeout, null,
Protocol.DEFAULT_DATABASE);
final GenericObjectPoolConfig poolConfig, final int timeout) {
this(masterName, sentinels, poolConfig, timeout, null,
Protocol.DEFAULT_DATABASE);
}
public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, final String password) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT,
password);
final GenericObjectPoolConfig poolConfig, final String password) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT,
password);
}
public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, int timeout,
final String password, final int database) {
final GenericObjectPoolConfig poolConfig, int timeout,
final String password, final int database) {
this.poolConfig = poolConfig;
this.timeout = timeout;
this.password = password;
this.database = database;
this.poolConfig = poolConfig;
this.timeout = timeout;
this.password = password;
this.database = database;
HostAndPort master = initSentinels(sentinels, masterName);
initPool(master);
HostAndPort master = initSentinels(sentinels, masterName);
initPool(master);
}
private volatile JedisFactory factory;
private volatile HostAndPort currentHostMaster;
public void destroy() {
for (MasterListener m : masterListeners) {
m.shutdown();
}
for (MasterListener m : masterListeners) {
m.shutdown();
}
super.destroy();
super.destroy();
}
public HostAndPort getCurrentHostMaster() {
return currentHostMaster;
return currentHostMaster;
}
private void initPool(HostAndPort master) {
if (!master.equals(currentHostMaster)) {
currentHostMaster = master;
if (factory == null) {
factory = new JedisFactory(master.getHost(), master.getPort(),
timeout, password, database);
initPool(poolConfig, factory);
} else {
factory.setHostAndPort(currentHostMaster);
// although we clear the pool, we still have to check the
// returned object
// in getResource, this call only clears idle instances, not
// borrowed instances
internalPool.clear();
}
if (!master.equals(currentHostMaster)) {
currentHostMaster = master;
if (factory == null) {
factory = new JedisFactory(master.getHost(), master.getPort(),
timeout, password, database);
initPool(poolConfig, factory);
} else {
factory.setHostAndPort(currentHostMaster);
// although we clear the pool, we still have to check the
// returned object
// in getResource, this call only clears idle instances, not
// borrowed instances
internalPool.clear();
}
log.info("Created JedisPool to master at " + master);
}
log.info("Created JedisPool to master at " + master);
}
}
private HostAndPort initSentinels(Set<String> sentinels,
final String masterName) {
final String masterName) {
HostAndPort master = null;
boolean sentinelAvailable = false;
HostAndPort master = null;
boolean sentinelAvailable = false;
log.info("Trying to find master from available Sentinels...");
log.info("Trying to find master from available Sentinels...");
for (String sentinel : sentinels) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel
.split(":")));
for (String sentinel : sentinels) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel
.split(":")));
log.fine("Connecting to Sentinel " + hap);
log.fine("Connecting to Sentinel " + hap);
Jedis jedis = null;
try {
jedis = new Jedis(hap.getHost(), hap.getPort());
Jedis jedis = null;
try {
jedis = new Jedis(hap.getHost(), hap.getPort());
List<String> masterAddr = jedis
.sentinelGetMasterAddrByName(masterName);
List<String> masterAddr = jedis
.sentinelGetMasterAddrByName(masterName);
// connected to sentinel...
sentinelAvailable = true;
// connected to sentinel...
sentinelAvailable = true;
if (masterAddr == null || masterAddr.size() != 2) {
log.warning("Can not get master addr, master name: "
+ masterName + ". Sentinel: " + hap + ".");
continue;
}
if (masterAddr == null || masterAddr.size() != 2) {
log.warning("Can not get master addr, master name: "
+ masterName + ". Sentinel: " + hap + ".");
continue;
}
master = toHostAndPort(masterAddr);
log.fine("Found Redis master at " + master);
break;
} catch (JedisConnectionException e) {
log.warning("Cannot connect to sentinel running @ " + hap
+ ". Trying next one.");
} finally {
if (jedis != null) {
jedis.close();
}
}
}
master = toHostAndPort(masterAddr);
log.fine("Found Redis master at " + master);
break;
} catch (JedisConnectionException e) {
log.warning("Cannot connect to sentinel running @ " + hap
+ ". Trying next one.");
} finally {
if (jedis != null) {
jedis.close();
}
}
}
if (master == null) {
if (sentinelAvailable) {
// can connect to sentinel, but master name seems to not
// monitored
throw new JedisException("Can connect to sentinel, but "
+ masterName + " seems to be not monitored...");
} else {
throw new JedisConnectionException(
"All sentinels down, cannot determine where is "
+ masterName + " master is running...");
}
}
if (master == null) {
if (sentinelAvailable) {
// can connect to sentinel, but master name seems to not
// monitored
throw new JedisException("Can connect to sentinel, but "
+ masterName + " seems to be not monitored...");
} else {
throw new JedisConnectionException(
"All sentinels down, cannot determine where is "
+ masterName + " master is running...");
}
}
log.info("Redis master running at " + master
+ ", starting Sentinel listeners...");
log.info("Redis master running at " + master
+ ", starting Sentinel listeners...");
for (String sentinel : sentinels) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel
.split(":")));
MasterListener masterListener = new MasterListener(masterName,
hap.getHost(), hap.getPort());
masterListeners.add(masterListener);
masterListener.start();
}
for (String sentinel : sentinels) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel
.split(":")));
MasterListener masterListener = new MasterListener(masterName,
hap.getHost(), hap.getPort());
masterListeners.add(masterListener);
masterListener.start();
}
return master;
return master;
}
private HostAndPort toHostAndPort(List<String> getMasterAddrByNameResult) {
String host = getMasterAddrByNameResult.get(0);
int port = Integer.parseInt(getMasterAddrByNameResult.get(1));
String host = getMasterAddrByNameResult.get(0);
int port = Integer.parseInt(getMasterAddrByNameResult.get(1));
return new HostAndPort(host, port);
return new HostAndPort(host, port);
}
@Override
public Jedis getResource() {
while (true) {
Jedis jedis = super.getResource();
jedis.setDataSource(this);
while (true) {
Jedis jedis = super.getResource();
jedis.setDataSource(this);
// get a reference because it can change concurrently
final HostAndPort master = currentHostMaster;
final HostAndPort connection = new HostAndPort(jedis.getClient()
.getHost(), jedis.getClient().getPort());
// get a reference because it can change concurrently
final HostAndPort master = currentHostMaster;
final HostAndPort connection = new HostAndPort(jedis.getClient()
.getHost(), jedis.getClient().getPort());
if (master.equals(connection)) {
// connected to the correct master
return jedis;
} else {
returnBrokenResource(jedis);
}
}
if (master.equals(connection)) {
// connected to the correct master
return jedis;
} else {
returnBrokenResource(jedis);
}
}
}
public void returnBrokenResource(final Jedis resource) {
if (resource != null) {
returnBrokenResourceObject(resource);
}
if (resource != null) {
returnBrokenResourceObject(resource);
}
}
public void returnResource(final Jedis resource) {
if (resource != null) {
resource.resetState();
returnResourceObject(resource);
}
if (resource != null) {
resource.resetState();
returnResourceObject(resource);
}
protected class JedisPubSubAdapter extends JedisPubSub {
@Override
public void onMessage(String channel, String message) {
}
@Override
public void onPMessage(String pattern, String channel, String message) {
}
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
}
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
}
}
protected class MasterListener extends Thread {
protected String masterName;
protected String host;
protected int port;
protected long subscribeRetryWaitTimeMillis = 5000;
protected Jedis j;
protected AtomicBoolean running = new AtomicBoolean(false);
protected String masterName;
protected String host;
protected int port;
protected long subscribeRetryWaitTimeMillis = 5000;
protected Jedis j;
protected AtomicBoolean running = new AtomicBoolean(false);
protected MasterListener() {
}
protected MasterListener() {
}
public MasterListener(String masterName, String host, int port) {
this.masterName = masterName;
this.host = host;
this.port = port;
}
public MasterListener(String masterName, String host, int port) {
this.masterName = masterName;
this.host = host;
this.port = port;
}
public MasterListener(String masterName, String host, int port,
long subscribeRetryWaitTimeMillis) {
this(masterName, host, port);
this.subscribeRetryWaitTimeMillis = subscribeRetryWaitTimeMillis;
}
public MasterListener(String masterName, String host, int port,
long subscribeRetryWaitTimeMillis) {
this(masterName, host, port);
this.subscribeRetryWaitTimeMillis = subscribeRetryWaitTimeMillis;
}
public void run() {
public void run() {
running.set(true);
running.set(true);
while (running.get()) {
while (running.get()) {
j = new Jedis(host, port);
j = new Jedis(host, port);
try {
j.subscribe(new JedisPubSubAdapter() {
@Override
public void onMessage(String channel, String message) {
log.fine("Sentinel " + host + ":" + port
+ " published: " + message + ".");
try {
j.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
log.fine("Sentinel " + host + ":" + port
+ " published: " + message + ".");
String[] switchMasterMsg = message.split(" ");
String[] switchMasterMsg = message.split(" ");
if (switchMasterMsg.length > 3) {
if (switchMasterMsg.length > 3) {
if (masterName.equals(switchMasterMsg[0])) {
initPool(toHostAndPort(Arrays.asList(
switchMasterMsg[3],
switchMasterMsg[4])));
} else {
log.fine("Ignoring message on +switch-master for master name "
+ switchMasterMsg[0]
+ ", our master name is "
+ masterName);
}
if (masterName.equals(switchMasterMsg[0])) {
initPool(toHostAndPort(Arrays.asList(
switchMasterMsg[3],
switchMasterMsg[4])));
} else {
log.fine("Ignoring message on +switch-master for master name "
+ switchMasterMsg[0]
+ ", our master name is "
+ masterName);
}
} else {
log.severe("Invalid message received on Sentinel "
+ host
+ ":"
+ port
+ " on channel +switch-master: "
+ message);
}
}
}, "+switch-master");
} else {
log.severe("Invalid message received on Sentinel "
+ host
+ ":"
+ port
+ " on channel +switch-master: "
+ message);
}
}
}, "+switch-master");
} catch (JedisConnectionException e) {
} catch (JedisConnectionException e) {
if (running.get()) {
log.severe("Lost connection to Sentinel at " + host
+ ":" + port
+ ". Sleeping 5000ms and retrying.");
try {
Thread.sleep(subscribeRetryWaitTimeMillis);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
log.fine("Unsubscribing from Sentinel at " + host + ":"
+ port);
}
}
}
}
if (running.get()) {
log.severe("Lost connection to Sentinel at " + host
+ ":" + port
+ ". Sleeping 5000ms and retrying.");
try {
Thread.sleep(subscribeRetryWaitTimeMillis);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
log.fine("Unsubscribing from Sentinel at " + host + ":"
+ port);
}
}
}
}
public void shutdown() {
try {
log.fine("Shutting down listener on " + host + ":" + port);
running.set(false);
// This isn't good, the Jedis object is not thread safe
j.disconnect();
} catch (Exception e) {
log.severe("Caught exception while shutting down: "
+ e.getMessage());
}
}
public void shutdown() {
try {
log.fine("Shutting down listener on " + host + ":" + port);
running.set(false);
// This isn't good, the Jedis object is not thread safe
j.disconnect();
} catch (Exception e) {
log.severe("Caught exception while shutting down: "
+ e.getMessage());
}
}
}
}

View File

@@ -7,7 +7,7 @@ import redis.clients.util.Sharded;
public class JedisShardInfo extends ShardInfo<Jedis> {
public String toString() {
return host + ":" + port + "*" + getWeight();
return host + ":" + port + "*" + getWeight();
}
private int timeout;
@@ -17,83 +17,83 @@ public class JedisShardInfo extends ShardInfo<Jedis> {
private String name = null;
public String getHost() {
return host;
return host;
}
public int getPort() {
return port;
return port;
}
public JedisShardInfo(String host) {
super(Sharded.DEFAULT_WEIGHT);
URI uri = URI.create(host);
if (uri.getScheme() != null && uri.getScheme().equals("redis")) {
this.host = uri.getHost();
this.port = uri.getPort();
this.password = uri.getUserInfo().split(":", 2)[1];
} else {
this.host = host;
this.port = Protocol.DEFAULT_PORT;
}
super(Sharded.DEFAULT_WEIGHT);
URI uri = URI.create(host);
if (uri.getScheme() != null && uri.getScheme().equals("redis")) {
this.host = uri.getHost();
this.port = uri.getPort();
this.password = uri.getUserInfo().split(":", 2)[1];
} else {
this.host = host;
this.port = Protocol.DEFAULT_PORT;
}
}
public JedisShardInfo(String host, String name) {
this(host, Protocol.DEFAULT_PORT, name);
this(host, Protocol.DEFAULT_PORT, name);
}
public JedisShardInfo(String host, int port) {
this(host, port, 2000);
this(host, port, 2000);
}
public JedisShardInfo(String host, int port, String name) {
this(host, port, 2000, name);
this(host, port, 2000, name);
}
public JedisShardInfo(String host, int port, int timeout) {
this(host, port, timeout, Sharded.DEFAULT_WEIGHT);
this(host, port, timeout, Sharded.DEFAULT_WEIGHT);
}
public JedisShardInfo(String host, int port, int timeout, String name) {
this(host, port, timeout, Sharded.DEFAULT_WEIGHT);
this.name = name;
this(host, port, timeout, Sharded.DEFAULT_WEIGHT);
this.name = name;
}
public JedisShardInfo(String host, int port, int timeout, int weight) {
super(weight);
this.host = host;
this.port = port;
this.timeout = timeout;
super(weight);
this.host = host;
this.port = port;
this.timeout = timeout;
}
public JedisShardInfo(URI uri) {
super(Sharded.DEFAULT_WEIGHT);
this.host = uri.getHost();
this.port = uri.getPort();
this.password = uri.getUserInfo().split(":", 2)[1];
super(Sharded.DEFAULT_WEIGHT);
this.host = uri.getHost();
this.port = uri.getPort();
this.password = uri.getUserInfo().split(":", 2)[1];
}
public String getPassword() {
return password;
return password;
}
public void setPassword(String auth) {
this.password = auth;
this.password = auth;
}
public int getTimeout() {
return timeout;
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
this.timeout = timeout;
}
public String getName() {
return name;
return name;
}
@Override
public Jedis createResource() {
return new Jedis(this);
return new Jedis(this);
}
}

View File

@@ -10,63 +10,63 @@ import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;
public class JedisSlotBasedConnectionHandler extends
JedisClusterConnectionHandler {
JedisClusterConnectionHandler {
public JedisSlotBasedConnectionHandler(Set<HostAndPort> nodes,
final GenericObjectPoolConfig poolConfig) {
super(nodes, poolConfig);
final GenericObjectPoolConfig poolConfig) {
super(nodes, poolConfig);
}
public Jedis getConnection() {
// In antirez's redis-rb-cluster implementation,
// getRandomConnection always return valid connection (able to
// ping-pong)
// or exception if all connections are invalid
// In antirez's redis-rb-cluster implementation,
// getRandomConnection always return valid connection (able to
// ping-pong)
// or exception if all connections are invalid
List<JedisPool> pools = getShuffledNodesPool();
List<JedisPool> pools = getShuffledNodesPool();
for (JedisPool pool : pools) {
Jedis jedis = null;
try {
jedis = pool.getResource();
for (JedisPool pool : pools) {
Jedis jedis = null;
try {
jedis = pool.getResource();
if (jedis == null) {
continue;
}
if (jedis == null) {
continue;
}
String result = jedis.ping();
String result = jedis.ping();
if (result.equalsIgnoreCase("pong"))
return jedis;
if (result.equalsIgnoreCase("pong"))
return jedis;
pool.returnBrokenResource(jedis);
} catch (JedisConnectionException ex) {
if (jedis != null) {
pool.returnBrokenResource(jedis);
}
}
}
pool.returnBrokenResource(jedis);
} catch (JedisConnectionException ex) {
if (jedis != null) {
pool.returnBrokenResource(jedis);
}
}
}
throw new JedisConnectionException("no reachable node in cluster");
throw new JedisConnectionException("no reachable node in cluster");
}
@Override
public Jedis getConnectionFromSlot(int slot) {
JedisPool connectionPool = cache.getSlotPool(slot);
if (connectionPool != null) {
// It can't guaranteed to get valid connection because of node
// assignment
return connectionPool.getResource();
} else {
return getConnection();
}
JedisPool connectionPool = cache.getSlotPool(slot);
if (connectionPool != null) {
// It can't guaranteed to get valid connection because of node
// assignment
return connectionPool.getResource();
} else {
return getConnection();
}
}
private List<JedisPool> getShuffledNodesPool() {
List<JedisPool> pools = new ArrayList<JedisPool>();
pools.addAll(cache.getNodes().values());
Collections.shuffle(pools);
return pools;
List<JedisPool> pools = new ArrayList<JedisPool>();
pools.addAll(cache.getNodes().values());
Collections.shuffle(pools);
return pools;
}
}

View File

@@ -40,7 +40,7 @@ public interface MultiKeyBinaryRedisPipeline {
Response<Long> smove(byte[] srckey, byte[] dstkey, byte[] member);
Response<Long> sort(byte[] key, SortingParams sortingParameters,
byte[] dstkey);
byte[] dstkey);
Response<Long> sort(byte[] key, byte[] dstkey);

View File

@@ -39,7 +39,7 @@ public interface MultiKeyCommandsPipeline {
Response<Long> smove(String srckey, String dstkey, String member);
Response<Long> sort(String key, SortingParams sortingParameters,
String dstkey);
String dstkey);
Response<Long> sort(String key, String dstkey);

View File

@@ -5,474 +5,474 @@ import java.util.Map;
import java.util.Set;
abstract class MultiKeyPipelineBase extends PipelineBase implements
BasicRedisPipeline, MultiKeyBinaryRedisPipeline,
MultiKeyCommandsPipeline, ClusterPipeline {
BasicRedisPipeline, MultiKeyBinaryRedisPipeline,
MultiKeyCommandsPipeline, ClusterPipeline {
protected Client client = null;
public Response<List<String>> brpop(String... args) {
client.brpop(args);
return getResponse(BuilderFactory.STRING_LIST);
client.brpop(args);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<List<String>> brpop(int timeout, String... keys) {
client.brpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST);
client.brpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<List<String>> blpop(String... args) {
client.blpop(args);
return getResponse(BuilderFactory.STRING_LIST);
client.blpop(args);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<List<String>> blpop(int timeout, String... keys) {
client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST);
client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<Map<String, String>> blpopMap(int timeout, String... keys) {
client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_MAP);
client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_MAP);
}
public Response<List<byte[]>> brpop(byte[]... args) {
client.brpop(args);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
client.brpop(args);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
public Response<List<String>> brpop(int timeout, byte[]... keys) {
client.brpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST);
client.brpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<Map<String, String>> brpopMap(int timeout, String... keys) {
client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_MAP);
client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_MAP);
}
public Response<List<byte[]>> blpop(byte[]... args) {
client.blpop(args);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
client.blpop(args);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
public Response<List<String>> blpop(int timeout, byte[]... keys) {
client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST);
client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<Long> del(String... keys) {
client.del(keys);
return getResponse(BuilderFactory.LONG);
client.del(keys);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> del(byte[]... keys) {
client.del(keys);
return getResponse(BuilderFactory.LONG);
client.del(keys);
return getResponse(BuilderFactory.LONG);
}
public Response<Set<String>> keys(String pattern) {
getClient(pattern).keys(pattern);
return getResponse(BuilderFactory.STRING_SET);
getClient(pattern).keys(pattern);
return getResponse(BuilderFactory.STRING_SET);
}
public Response<Set<byte[]>> keys(byte[] pattern) {
getClient(pattern).keys(pattern);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
getClient(pattern).keys(pattern);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<List<String>> mget(String... keys) {
client.mget(keys);
return getResponse(BuilderFactory.STRING_LIST);
client.mget(keys);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<List<byte[]>> mget(byte[]... keys) {
client.mget(keys);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
client.mget(keys);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
public Response<String> mset(String... keysvalues) {
client.mset(keysvalues);
return getResponse(BuilderFactory.STRING);
client.mset(keysvalues);
return getResponse(BuilderFactory.STRING);
}
public Response<String> mset(byte[]... keysvalues) {
client.mset(keysvalues);
return getResponse(BuilderFactory.STRING);
client.mset(keysvalues);
return getResponse(BuilderFactory.STRING);
}
public Response<Long> msetnx(String... keysvalues) {
client.msetnx(keysvalues);
return getResponse(BuilderFactory.LONG);
client.msetnx(keysvalues);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> msetnx(byte[]... keysvalues) {
client.msetnx(keysvalues);
return getResponse(BuilderFactory.LONG);
client.msetnx(keysvalues);
return getResponse(BuilderFactory.LONG);
}
public Response<String> rename(String oldkey, String newkey) {
client.rename(oldkey, newkey);
return getResponse(BuilderFactory.STRING);
client.rename(oldkey, newkey);
return getResponse(BuilderFactory.STRING);
}
public Response<String> rename(byte[] oldkey, byte[] newkey) {
client.rename(oldkey, newkey);
return getResponse(BuilderFactory.STRING);
client.rename(oldkey, newkey);
return getResponse(BuilderFactory.STRING);
}
public Response<Long> renamenx(String oldkey, String newkey) {
client.renamenx(oldkey, newkey);
return getResponse(BuilderFactory.LONG);
client.renamenx(oldkey, newkey);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> renamenx(byte[] oldkey, byte[] newkey) {
client.renamenx(oldkey, newkey);
return getResponse(BuilderFactory.LONG);
client.renamenx(oldkey, newkey);
return getResponse(BuilderFactory.LONG);
}
public Response<String> rpoplpush(String srckey, String dstkey) {
client.rpoplpush(srckey, dstkey);
return getResponse(BuilderFactory.STRING);
client.rpoplpush(srckey, dstkey);
return getResponse(BuilderFactory.STRING);
}
public Response<byte[]> rpoplpush(byte[] srckey, byte[] dstkey) {
client.rpoplpush(srckey, dstkey);
return getResponse(BuilderFactory.BYTE_ARRAY);
client.rpoplpush(srckey, dstkey);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<Set<String>> sdiff(String... keys) {
client.sdiff(keys);
return getResponse(BuilderFactory.STRING_SET);
client.sdiff(keys);
return getResponse(BuilderFactory.STRING_SET);
}
public Response<Set<byte[]>> sdiff(byte[]... keys) {
client.sdiff(keys);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
client.sdiff(keys);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<Long> sdiffstore(String dstkey, String... keys) {
client.sdiffstore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
client.sdiffstore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> sdiffstore(byte[] dstkey, byte[]... keys) {
client.sdiffstore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
client.sdiffstore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
}
public Response<Set<String>> sinter(String... keys) {
client.sinter(keys);
return getResponse(BuilderFactory.STRING_SET);
client.sinter(keys);
return getResponse(BuilderFactory.STRING_SET);
}
public Response<Set<byte[]>> sinter(byte[]... keys) {
client.sinter(keys);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
client.sinter(keys);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<Long> sinterstore(String dstkey, String... keys) {
client.sinterstore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
client.sinterstore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> sinterstore(byte[] dstkey, byte[]... keys) {
client.sinterstore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
client.sinterstore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> smove(String srckey, String dstkey, String member) {
client.smove(srckey, dstkey, member);
return getResponse(BuilderFactory.LONG);
client.smove(srckey, dstkey, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> smove(byte[] srckey, byte[] dstkey, byte[] member) {
client.smove(srckey, dstkey, member);
return getResponse(BuilderFactory.LONG);
client.smove(srckey, dstkey, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> sort(String key, SortingParams sortingParameters,
String dstkey) {
client.sort(key, sortingParameters, dstkey);
return getResponse(BuilderFactory.LONG);
String dstkey) {
client.sort(key, sortingParameters, dstkey);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> sort(byte[] key, SortingParams sortingParameters,
byte[] dstkey) {
client.sort(key, sortingParameters, dstkey);
return getResponse(BuilderFactory.LONG);
byte[] dstkey) {
client.sort(key, sortingParameters, dstkey);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> sort(String key, String dstkey) {
client.sort(key, dstkey);
return getResponse(BuilderFactory.LONG);
client.sort(key, dstkey);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> sort(byte[] key, byte[] dstkey) {
client.sort(key, dstkey);
return getResponse(BuilderFactory.LONG);
client.sort(key, dstkey);
return getResponse(BuilderFactory.LONG);
}
public Response<Set<String>> sunion(String... keys) {
client.sunion(keys);
return getResponse(BuilderFactory.STRING_SET);
client.sunion(keys);
return getResponse(BuilderFactory.STRING_SET);
}
public Response<Set<byte[]>> sunion(byte[]... keys) {
client.sunion(keys);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
client.sunion(keys);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<Long> sunionstore(String dstkey, String... keys) {
client.sunionstore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
client.sunionstore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> sunionstore(byte[] dstkey, byte[]... keys) {
client.sunionstore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
client.sunionstore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
}
public Response<String> watch(String... keys) {
client.watch(keys);
return getResponse(BuilderFactory.STRING);
client.watch(keys);
return getResponse(BuilderFactory.STRING);
}
public Response<String> watch(byte[]... keys) {
client.watch(keys);
return getResponse(BuilderFactory.STRING);
client.watch(keys);
return getResponse(BuilderFactory.STRING);
}
public Response<Long> zinterstore(String dstkey, String... sets) {
client.zinterstore(dstkey, sets);
return getResponse(BuilderFactory.LONG);
client.zinterstore(dstkey, sets);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zinterstore(byte[] dstkey, byte[]... sets) {
client.zinterstore(dstkey, sets);
return getResponse(BuilderFactory.LONG);
client.zinterstore(dstkey, sets);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zinterstore(String dstkey, ZParams params,
String... sets) {
client.zinterstore(dstkey, params, sets);
return getResponse(BuilderFactory.LONG);
String... sets) {
client.zinterstore(dstkey, params, sets);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zinterstore(byte[] dstkey, ZParams params,
byte[]... sets) {
client.zinterstore(dstkey, params, sets);
return getResponse(BuilderFactory.LONG);
byte[]... sets) {
client.zinterstore(dstkey, params, sets);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zunionstore(String dstkey, String... sets) {
client.zunionstore(dstkey, sets);
return getResponse(BuilderFactory.LONG);
client.zunionstore(dstkey, sets);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zunionstore(byte[] dstkey, byte[]... sets) {
client.zunionstore(dstkey, sets);
return getResponse(BuilderFactory.LONG);
client.zunionstore(dstkey, sets);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zunionstore(String dstkey, ZParams params,
String... sets) {
client.zunionstore(dstkey, params, sets);
return getResponse(BuilderFactory.LONG);
String... sets) {
client.zunionstore(dstkey, params, sets);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zunionstore(byte[] dstkey, ZParams params,
byte[]... sets) {
client.zunionstore(dstkey, params, sets);
return getResponse(BuilderFactory.LONG);
byte[]... sets) {
client.zunionstore(dstkey, params, sets);
return getResponse(BuilderFactory.LONG);
}
public Response<String> bgrewriteaof() {
client.bgrewriteaof();
return getResponse(BuilderFactory.STRING);
client.bgrewriteaof();
return getResponse(BuilderFactory.STRING);
}
public Response<String> bgsave() {
client.bgsave();
return getResponse(BuilderFactory.STRING);
client.bgsave();
return getResponse(BuilderFactory.STRING);
}
public Response<String> configGet(String pattern) {
client.configGet(pattern);
return getResponse(BuilderFactory.STRING);
client.configGet(pattern);
return getResponse(BuilderFactory.STRING);
}
public Response<String> configSet(String parameter, String value) {
client.configSet(parameter, value);
return getResponse(BuilderFactory.STRING);
client.configSet(parameter, value);
return getResponse(BuilderFactory.STRING);
}
public Response<String> brpoplpush(String source, String destination,
int timeout) {
client.brpoplpush(source, destination, timeout);
return getResponse(BuilderFactory.STRING);
int timeout) {
client.brpoplpush(source, destination, timeout);
return getResponse(BuilderFactory.STRING);
}
public Response<byte[]> brpoplpush(byte[] source, byte[] destination,
int timeout) {
client.brpoplpush(source, destination, timeout);
return getResponse(BuilderFactory.BYTE_ARRAY);
int timeout) {
client.brpoplpush(source, destination, timeout);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<String> configResetStat() {
client.configResetStat();
return getResponse(BuilderFactory.STRING);
client.configResetStat();
return getResponse(BuilderFactory.STRING);
}
public Response<String> save() {
client.save();
return getResponse(BuilderFactory.STRING);
client.save();
return getResponse(BuilderFactory.STRING);
}
public Response<Long> lastsave() {
client.lastsave();
return getResponse(BuilderFactory.LONG);
client.lastsave();
return getResponse(BuilderFactory.LONG);
}
public Response<Long> publish(String channel, String message) {
client.publish(channel, message);
return getResponse(BuilderFactory.LONG);
client.publish(channel, message);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> publish(byte[] channel, byte[] message) {
client.publish(channel, message);
return getResponse(BuilderFactory.LONG);
client.publish(channel, message);
return getResponse(BuilderFactory.LONG);
}
public Response<String> randomKey() {
client.randomKey();
return getResponse(BuilderFactory.STRING);
client.randomKey();
return getResponse(BuilderFactory.STRING);
}
public Response<byte[]> randomKeyBinary() {
client.randomKey();
return getResponse(BuilderFactory.BYTE_ARRAY);
client.randomKey();
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<String> flushDB() {
client.flushDB();
return getResponse(BuilderFactory.STRING);
client.flushDB();
return getResponse(BuilderFactory.STRING);
}
public Response<String> flushAll() {
client.flushAll();
return getResponse(BuilderFactory.STRING);
client.flushAll();
return getResponse(BuilderFactory.STRING);
}
public Response<String> info() {
client.info();
return getResponse(BuilderFactory.STRING);
client.info();
return getResponse(BuilderFactory.STRING);
}
public Response<List<String>> time() {
client.time();
return getResponse(BuilderFactory.STRING_LIST);
client.time();
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<Long> dbSize() {
client.dbSize();
return getResponse(BuilderFactory.LONG);
client.dbSize();
return getResponse(BuilderFactory.LONG);
}
public Response<String> shutdown() {
client.shutdown();
return getResponse(BuilderFactory.STRING);
client.shutdown();
return getResponse(BuilderFactory.STRING);
}
public Response<String> ping() {
client.ping();
return getResponse(BuilderFactory.STRING);
client.ping();
return getResponse(BuilderFactory.STRING);
}
public Response<String> select(int index) {
client.select(index);
return getResponse(BuilderFactory.STRING);
client.select(index);
return getResponse(BuilderFactory.STRING);
}
public Response<Long> bitop(BitOP op, byte[] destKey, byte[]... srcKeys) {
client.bitop(op, destKey, srcKeys);
return getResponse(BuilderFactory.LONG);
client.bitop(op, destKey, srcKeys);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> bitop(BitOP op, String destKey, String... srcKeys) {
client.bitop(op, destKey, srcKeys);
return getResponse(BuilderFactory.LONG);
client.bitop(op, destKey, srcKeys);
return getResponse(BuilderFactory.LONG);
}
public Response<String> clusterNodes() {
client.clusterNodes();
return getResponse(BuilderFactory.STRING);
client.clusterNodes();
return getResponse(BuilderFactory.STRING);
}
public Response<String> clusterMeet(final String ip, final int port) {
client.clusterMeet(ip, port);
return getResponse(BuilderFactory.STRING);
client.clusterMeet(ip, port);
return getResponse(BuilderFactory.STRING);
}
public Response<String> clusterAddSlots(final int... slots) {
client.clusterAddSlots(slots);
return getResponse(BuilderFactory.STRING);
client.clusterAddSlots(slots);
return getResponse(BuilderFactory.STRING);
}
public Response<String> clusterDelSlots(final int... slots) {
client.clusterDelSlots(slots);
return getResponse(BuilderFactory.STRING);
client.clusterDelSlots(slots);
return getResponse(BuilderFactory.STRING);
}
public Response<String> clusterInfo() {
client.clusterInfo();
return getResponse(BuilderFactory.STRING);
client.clusterInfo();
return getResponse(BuilderFactory.STRING);
}
public Response<List<String>> clusterGetKeysInSlot(final int slot,
final int count) {
client.clusterGetKeysInSlot(slot, count);
return getResponse(BuilderFactory.STRING_LIST);
final int count) {
client.clusterGetKeysInSlot(slot, count);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<String> clusterSetSlotNode(final int slot,
final String nodeId) {
client.clusterSetSlotNode(slot, nodeId);
return getResponse(BuilderFactory.STRING);
final String nodeId) {
client.clusterSetSlotNode(slot, nodeId);
return getResponse(BuilderFactory.STRING);
}
public Response<String> clusterSetSlotMigrating(final int slot,
final String nodeId) {
client.clusterSetSlotMigrating(slot, nodeId);
return getResponse(BuilderFactory.STRING);
final String nodeId) {
client.clusterSetSlotMigrating(slot, nodeId);
return getResponse(BuilderFactory.STRING);
}
public Response<String> clusterSetSlotImporting(final int slot,
final String nodeId) {
client.clusterSetSlotImporting(slot, nodeId);
return getResponse(BuilderFactory.STRING);
final String nodeId) {
client.clusterSetSlotImporting(slot, nodeId);
return getResponse(BuilderFactory.STRING);
}
@Override
public Response<String> pfmerge(byte[] destkey, byte[]... sourcekeys) {
client.pfmerge(destkey, sourcekeys);
return getResponse(BuilderFactory.STRING);
client.pfmerge(destkey, sourcekeys);
return getResponse(BuilderFactory.STRING);
}
@Override
public Response<String> pfmerge(String destkey, String... sourcekeys) {
client.pfmerge(destkey, sourcekeys);
return getResponse(BuilderFactory.STRING);
client.pfmerge(destkey, sourcekeys);
return getResponse(BuilderFactory.STRING);
}
@Override
public Response<Long> pfcount(String... keys) {
client.pfcount(keys);
return getResponse(BuilderFactory.LONG);
client.pfcount(keys);
return getResponse(BuilderFactory.LONG);
}
@Override
public Response<Long> pfcount(final byte[]... keys) {
client.pfcount(keys);
return getResponse(BuilderFactory.LONG);
client.pfcount(keys);
return getResponse(BuilderFactory.LONG);
}
}

View File

@@ -10,81 +10,81 @@ public class Pipeline extends MultiKeyPipelineBase {
private MultiResponseBuilder currentMulti;
private class MultiResponseBuilder extends Builder<List<Object>> {
private List<Response<?>> responses = new ArrayList<Response<?>>();
private List<Response<?>> responses = new ArrayList<Response<?>>();
@Override
public List<Object> build(Object data) {
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) data;
List<Object> values = new ArrayList<Object>();
@Override
public List<Object> build(Object data) {
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) data;
List<Object> values = new ArrayList<Object>();
if (list.size() != responses.size()) {
throw new JedisDataException("Expected data size "
+ responses.size() + " but was " + list.size());
}
if (list.size() != responses.size()) {
throw new JedisDataException("Expected data size "
+ responses.size() + " but was " + list.size());
}
for (int i = 0; i < list.size(); i++) {
Response<?> response = responses.get(i);
response.set(list.get(i));
Object builtResponse;
try {
builtResponse = response.get();
} catch (JedisDataException e) {
builtResponse = e;
}
values.add(builtResponse);
}
return values;
}
for (int i = 0; i < list.size(); i++) {
Response<?> response = responses.get(i);
response.set(list.get(i));
Object builtResponse;
try {
builtResponse = response.get();
} catch (JedisDataException e) {
builtResponse = e;
}
values.add(builtResponse);
}
return values;
}
public void setResponseDependency(Response<?> dependency) {
for (Response<?> response : responses) {
response.setDependency(dependency);
}
}
public void setResponseDependency(Response<?> dependency) {
for (Response<?> response : responses) {
response.setDependency(dependency);
}
}
public void addResponse(Response<?> response) {
responses.add(response);
}
public void addResponse(Response<?> response) {
responses.add(response);
}
}
@Override
protected <T> Response<T> getResponse(Builder<T> builder) {
if (currentMulti != null) {
super.getResponse(BuilderFactory.STRING); // Expected QUEUED
if (currentMulti != null) {
super.getResponse(BuilderFactory.STRING); // Expected QUEUED
Response<T> lr = new Response<T>(builder);
currentMulti.addResponse(lr);
return lr;
} else {
return super.getResponse(builder);
}
Response<T> lr = new Response<T>(builder);
currentMulti.addResponse(lr);
return lr;
} else {
return super.getResponse(builder);
}
}
public void setClient(Client client) {
this.client = client;
this.client = client;
}
@Override
protected Client getClient(byte[] key) {
return client;
return client;
}
@Override
protected Client getClient(String key) {
return client;
return client;
}
public void clear() {
if (isInMulti()) {
discard();
}
if (isInMulti()) {
discard();
}
sync();
sync();
}
public boolean isInMulti() {
return currentMulti != null;
return currentMulti != null;
}
/**
@@ -93,12 +93,12 @@ public class Pipeline extends MultiKeyPipelineBase {
* the different Response<?> of the commands you execute.
*/
public void sync() {
if (getPipelinedResponseLength() > 0) {
if (getPipelinedResponseLength() > 0) {
List<Object> unformatted = client.getMany(getPipelinedResponseLength());
for (Object o : unformatted) {
generateResponse(o);
}
}
}
}
/**
* Synchronize pipeline by reading all responses. This operation close the
@@ -126,33 +126,33 @@ public class Pipeline extends MultiKeyPipelineBase {
}
public Response<String> discard() {
if (currentMulti == null)
throw new JedisDataException("DISCARD without MULTI");
client.discard();
currentMulti = null;
return getResponse(BuilderFactory.STRING);
if (currentMulti == null)
throw new JedisDataException("DISCARD without MULTI");
client.discard();
currentMulti = null;
return getResponse(BuilderFactory.STRING);
}
public Response<List<Object>> exec() {
if (currentMulti == null)
throw new JedisDataException("EXEC without MULTI");
if (currentMulti == null)
throw new JedisDataException("EXEC without MULTI");
client.exec();
Response<List<Object>> response = super.getResponse(currentMulti);
currentMulti.setResponseDependency(response);
currentMulti = null;
return response;
client.exec();
Response<List<Object>> response = super.getResponse(currentMulti);
currentMulti.setResponseDependency(response);
currentMulti = null;
return response;
}
public Response<String> multi() {
if (currentMulti != null)
throw new JedisDataException("MULTI calls can not be nested");
if (currentMulti != null)
throw new JedisDataException("MULTI calls can not be nested");
client.multi();
Response<String> response = getResponse(BuilderFactory.STRING); // Expecting
// OK
currentMulti = new MultiResponseBuilder();
return response;
client.multi();
Response<String> response = getResponse(BuilderFactory.STRING); // Expecting
// OK
currentMulti = new MultiResponseBuilder();
return response;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -67,174 +67,168 @@ public final class Protocol {
public static final String PUBSUB_NUM_PAT = "numpat";
private Protocol() {
// this prevent the class from instantiation
// this prevent the class from instantiation
}
public static void sendCommand(final RedisOutputStream os,
final Command command, final byte[]... args) {
sendCommand(os, command.raw, args);
final Command command, final byte[]... args) {
sendCommand(os, command.raw, args);
}
private static void sendCommand(final RedisOutputStream os,
final byte[] command, final byte[]... args) {
try {
os.write(ASTERISK_BYTE);
os.writeIntCrLf(args.length + 1);
os.write(DOLLAR_BYTE);
os.writeIntCrLf(command.length);
os.write(command);
os.writeCrLf();
final byte[] command, final byte[]... args) {
try {
os.write(ASTERISK_BYTE);
os.writeIntCrLf(args.length + 1);
os.write(DOLLAR_BYTE);
os.writeIntCrLf(command.length);
os.write(command);
os.writeCrLf();
for (final byte[] arg : args) {
os.write(DOLLAR_BYTE);
os.writeIntCrLf(arg.length);
os.write(arg);
os.writeCrLf();
}
} catch (IOException e) {
throw new JedisConnectionException(e);
}
for (final byte[] arg : args) {
os.write(DOLLAR_BYTE);
os.writeIntCrLf(arg.length);
os.write(arg);
os.writeCrLf();
}
} catch (IOException e) {
throw new JedisConnectionException(e);
}
}
private static void processError(final RedisInputStream is) {
String message = is.readLine();
// TODO: I'm not sure if this is the best way to do this.
// Maybe Read only first 5 bytes instead?
if (message.startsWith(MOVED_RESPONSE)) {
String[] movedInfo = parseTargetHostAndSlot(message);
throw new JedisMovedDataException(message, new HostAndPort(
movedInfo[1], Integer.valueOf(movedInfo[2])),
Integer.valueOf(movedInfo[0]));
} else if (message.startsWith(ASK_RESPONSE)) {
String[] askInfo = parseTargetHostAndSlot(message);
throw new JedisAskDataException(message, new HostAndPort(
askInfo[1], Integer.valueOf(askInfo[2])),
Integer.valueOf(askInfo[0]));
} else if (message.startsWith(CLUSTERDOWN_RESPONSE)) {
throw new JedisClusterException(message);
}
throw new JedisDataException(message);
String message = is.readLine();
// TODO: I'm not sure if this is the best way to do this.
// Maybe Read only first 5 bytes instead?
if (message.startsWith(MOVED_RESPONSE)) {
String[] movedInfo = parseTargetHostAndSlot(message);
throw new JedisMovedDataException(message, new HostAndPort(
movedInfo[1], Integer.valueOf(movedInfo[2])),
Integer.valueOf(movedInfo[0]));
} else if (message.startsWith(ASK_RESPONSE)) {
String[] askInfo = parseTargetHostAndSlot(message);
throw new JedisAskDataException(message, new HostAndPort(
askInfo[1], Integer.valueOf(askInfo[2])),
Integer.valueOf(askInfo[0]));
} else if (message.startsWith(CLUSTERDOWN_RESPONSE)) {
throw new JedisClusterException(message);
}
throw new JedisDataException(message);
}
private static String[] parseTargetHostAndSlot(
String clusterRedirectResponse) {
String[] response = new String[3];
String[] messageInfo = clusterRedirectResponse.split(" ");
String[] targetHostAndPort = messageInfo[2].split(":");
response[0] = messageInfo[1];
response[1] = targetHostAndPort[0];
response[2] = targetHostAndPort[1];
return response;
String clusterRedirectResponse) {
String[] response = new String[3];
String[] messageInfo = clusterRedirectResponse.split(" ");
String[] targetHostAndPort = messageInfo[2].split(":");
response[0] = messageInfo[1];
response[1] = targetHostAndPort[0];
response[2] = targetHostAndPort[1];
return response;
}
private static Object process(final RedisInputStream is) {
try {
byte b = is.readByte();
if (b == MINUS_BYTE) {
processError(is);
} else if (b == ASTERISK_BYTE) {
return processMultiBulkReply(is);
} else if (b == COLON_BYTE) {
return processInteger(is);
} else if (b == DOLLAR_BYTE) {
return processBulkReply(is);
} else if (b == PLUS_BYTE) {
return processStatusCodeReply(is);
} else {
throw new JedisConnectionException("Unknown reply: " + (char) b);
}
} catch (IOException e) {
throw new JedisConnectionException(e);
}
return null;
final byte b = is.readByte();
if (b == PLUS_BYTE) {
return processStatusCodeReply(is);
} else if (b == DOLLAR_BYTE) {
return processBulkReply(is);
} else if (b == ASTERISK_BYTE) {
return processMultiBulkReply(is);
} else if (b == COLON_BYTE) {
return processInteger(is);
} else if (b == MINUS_BYTE) {
processError(is);
return null;
} else {
throw new JedisConnectionException("Unknown reply: " + (char) b);
}
}
private static byte[] processStatusCodeReply(final RedisInputStream is) {
return SafeEncoder.encode(is.readLine());
return is.readLineBytes();
}
private static byte[] processBulkReply(final RedisInputStream is) {
int len = Integer.parseInt(is.readLine());
if (len == -1) {
return null;
}
byte[] read = new byte[len];
int offset = 0;
try {
while (offset < len) {
int size = is.read(read, offset, (len - offset));
if (size == -1)
throw new JedisConnectionException(
"It seems like server has closed the connection.");
offset += size;
}
// read 2 more bytes for the command delimiter
is.readByte();
is.readByte();
} catch (IOException e) {
throw new JedisConnectionException(e);
}
final int len = is.readIntCrLf();
if (len == -1) {
return null;
}
return read;
final byte[] read = new byte[len];
int offset = 0;
while (offset < len) {
final int size = is.read(read, offset, (len - offset));
if (size == -1)
throw new JedisConnectionException(
"It seems like server has closed the connection.");
offset += size;
}
// read 2 more bytes for the command delimiter
is.readByte();
is.readByte();
return read;
}
private static Long processInteger(final RedisInputStream is) {
String num = is.readLine();
return Long.valueOf(num);
return is.readLongCrLf();
}
private static List<Object> processMultiBulkReply(final RedisInputStream is) {
int num = Integer.parseInt(is.readLine());
if (num == -1) {
return null;
}
List<Object> ret = new ArrayList<Object>(num);
for (int i = 0; i < num; i++) {
try {
ret.add(process(is));
} catch (JedisDataException e) {
ret.add(e);
}
}
return ret;
final int num = is.readIntCrLf();
if (num == -1) {
return null;
}
final List<Object> ret = new ArrayList<Object>(num);
for (int i = 0; i < num; i++) {
try {
ret.add(process(is));
} catch (JedisDataException e) {
ret.add(e);
}
}
return ret;
}
public static Object read(final RedisInputStream is) {
return process(is);
return process(is);
}
public static final byte[] toByteArray(final boolean value) {
return toByteArray(value ? 1 : 0);
return toByteArray(value ? 1 : 0);
}
public static final byte[] toByteArray(final int value) {
return SafeEncoder.encode(String.valueOf(value));
return SafeEncoder.encode(String.valueOf(value));
}
public static final byte[] toByteArray(final long value) {
return SafeEncoder.encode(String.valueOf(value));
return SafeEncoder.encode(String.valueOf(value));
}
public static final byte[] toByteArray(final double value) {
return SafeEncoder.encode(String.valueOf(value));
return SafeEncoder.encode(String.valueOf(value));
}
public static enum Command {
PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, ZLEXCOUNT, ZRANGEBYLEX, ZREVRANGEBYLEX, ZREMRANGEBYLEX, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, BITPOS, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING, PFADD, PFCOUNT, PFMERGE;
PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, ZLEXCOUNT, ZRANGEBYLEX, ZREVRANGEBYLEX, ZREMRANGEBYLEX, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, BITPOS, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING, PFADD, PFCOUNT, PFMERGE;
public final byte[] raw;
public final byte[] raw;
Command() {
raw = SafeEncoder.encode(this.name());
}
Command() {
raw = SafeEncoder.encode(this.name());
}
}
public static enum Keyword {
AGGREGATE, ALPHA, ASC, BY, DESC, GET, LIMIT, MESSAGE, NO, NOSORT, PMESSAGE, PSUBSCRIBE, PUNSUBSCRIBE, OK, ONE, QUEUED, SET, STORE, SUBSCRIBE, UNSUBSCRIBE, WEIGHTS, WITHSCORES, RESETSTAT, RESET, FLUSH, EXISTS, LOAD, KILL, LEN, REFCOUNT, ENCODING, IDLETIME, AND, OR, XOR, NOT, GETNAME, SETNAME, LIST, MATCH, COUNT;
public final byte[] raw;
AGGREGATE, ALPHA, ASC, BY, DESC, GET, LIMIT, MESSAGE, NO, NOSORT, PMESSAGE, PSUBSCRIBE, PUNSUBSCRIBE, OK, ONE, QUEUED, SET, STORE, SUBSCRIBE, UNSUBSCRIBE, WEIGHTS, WITHSCORES, RESETSTAT, RESET, FLUSH, EXISTS, LOAD, KILL, LEN, REFCOUNT, ENCODING, IDLETIME, AND, OR, XOR, NOT, GETNAME, SETNAME, LIST, MATCH, COUNT;
public final byte[] raw;
Keyword() {
raw = SafeEncoder.encode(this.name().toLowerCase());
}
Keyword() {
raw = SafeEncoder.encode(this.name().toLowerCase());
}
}
}

View File

@@ -7,28 +7,28 @@ public class Queable {
private Queue<Response<?>> pipelinedResponses = new LinkedList<Response<?>>();
protected void clean() {
pipelinedResponses.clear();
pipelinedResponses.clear();
}
protected Response<?> generateResponse(Object data) {
Response<?> response = pipelinedResponses.poll();
if (response != null) {
response.set(data);
}
return response;
Response<?> response = pipelinedResponses.poll();
if (response != null) {
response.set(data);
}
return response;
}
protected <T> Response<T> getResponse(Builder<T> builder) {
Response<T> lr = new Response<T>(builder);
pipelinedResponses.add(lr);
return lr;
Response<T> lr = new Response<T>(builder);
pipelinedResponses.add(lr);
return lr;
}
protected boolean hasPipelinedResponse() {
return pipelinedResponses.size() > 0;
return pipelinedResponses.size() > 0;
}
protected int getPipelinedResponseLength() {
return pipelinedResponses.size();
return pipelinedResponses.size();
}
}

View File

@@ -67,7 +67,7 @@ public interface RedisPipeline {
Response<String> lindex(String key, long index);
Response<Long> linsert(String key, BinaryClient.LIST_POSITION where,
String pivot, String value);
String pivot, String value);
Response<Long> llen(String key);
@@ -146,26 +146,26 @@ public interface RedisPipeline {
Response<Set<String>> zrangeByScore(String key, String min, String max);
Response<Set<String>> zrangeByScore(String key, double min, double max,
int offset, int count);
int offset, int count);
Response<Set<Tuple>> zrangeByScoreWithScores(String key, double min,
double max);
double max);
Response<Set<Tuple>> zrangeByScoreWithScores(String key, double min,
double max, int offset, int count);
double max, int offset, int count);
Response<Set<String>> zrevrangeByScore(String key, double max, double min);
Response<Set<String>> zrevrangeByScore(String key, String max, String min);
Response<Set<String>> zrevrangeByScore(String key, double max, double min,
int offset, int count);
int offset, int count);
Response<Set<Tuple>> zrevrangeByScoreWithScores(String key, double max,
double min);
double min);
Response<Set<Tuple>> zrevrangeByScoreWithScores(String key, double max,
double min, int offset, int count);
double min, int offset, int count);
Response<Set<Tuple>> zrangeWithScores(String key, long start, long end);
@@ -186,22 +186,22 @@ public interface RedisPipeline {
Response<Double> zscore(String key, String member);
Response<Long> zlexcount(final String key, final String min,
final String max);
final String max);
Response<Set<String>> zrangeByLex(final String key, final String min,
final String max);
final String max);
Response<Set<String>> zrangeByLex(final String key, final String min,
final String max, final int offset, final int count);
final String max, final int offset, final int count);
Response<Set<String>> zrevrangeByLex(final String key, final String max,
final String min);
final String min);
Response<Set<String>> zrevrangeByLex(final String key, final String max,
final String min, final int offset, final int count);
final String min, final int offset, final int count);
Response<Long> zremrangeByLex(final String key, final String start,
final String end);
final String end);
Response<Long> bitcount(String key);

View File

@@ -12,50 +12,50 @@ public class Response<T> {
private boolean requestDependencyBuild = false;
public Response(Builder<T> b) {
this.builder = b;
this.builder = b;
}
public void set(Object data) {
this.data = data;
set = true;
this.data = data;
set = true;
}
public T get() {
// if response has dependency response and dependency is not built,
// build it first and no more!!
if (!requestDependencyBuild && dependency != null && dependency.set
&& !dependency.built) {
requestDependencyBuild = true;
dependency.build();
}
if (!set) {
throw new JedisDataException(
"Please close pipeline or multi block before calling this method.");
}
if (!built) {
build();
}
return response;
// if response has dependency response and dependency is not built,
// build it first and no more!!
if (!requestDependencyBuild && dependency != null && dependency.set
&& !dependency.built) {
requestDependencyBuild = true;
dependency.build();
}
if (!set) {
throw new JedisDataException(
"Please close pipeline or multi block before calling this method.");
}
if (!built) {
build();
}
return response;
}
public void setDependency(Response<?> dependency) {
this.dependency = dependency;
this.requestDependencyBuild = false;
this.dependency = dependency;
this.requestDependencyBuild = false;
}
private void build() {
if (data != null) {
if (data instanceof JedisDataException) {
throw new JedisDataException((JedisDataException) data);
}
response = builder.build(data);
}
data = null;
built = true;
if (data != null) {
if (data instanceof JedisDataException) {
throw new JedisDataException((JedisDataException) data);
}
response = builder.build(data);
}
data = null;
built = true;
}
public String toString() {
return "Response " + builder.toString();
return "Response " + builder.toString();
}
}

View File

@@ -14,27 +14,27 @@ public class ScanParams {
private List<byte[]> params = new ArrayList<byte[]>();
public final static String SCAN_POINTER_START = String.valueOf(0);
public final static byte[] SCAN_POINTER_START_BINARY = SafeEncoder
.encode(SCAN_POINTER_START);
.encode(SCAN_POINTER_START);
public ScanParams match(final byte[] pattern) {
params.add(MATCH.raw);
params.add(pattern);
return this;
params.add(MATCH.raw);
params.add(pattern);
return this;
}
public ScanParams match(final String pattern) {
params.add(MATCH.raw);
params.add(SafeEncoder.encode(pattern));
return this;
params.add(MATCH.raw);
params.add(SafeEncoder.encode(pattern));
return this;
}
public ScanParams count(final int count) {
params.add(COUNT.raw);
params.add(Protocol.toByteArray(count));
return this;
params.add(COUNT.raw);
params.add(Protocol.toByteArray(count));
return this;
}
public Collection<byte[]> getParams() {
return Collections.unmodifiableCollection(params);
return Collections.unmodifiableCollection(params);
}
}

View File

@@ -9,23 +9,23 @@ public class ScanResult<T> {
private List<T> results;
public ScanResult(String cursor, List<T> results) {
this(SafeEncoder.encode(cursor), results);
this(SafeEncoder.encode(cursor), results);
}
public ScanResult(byte[] cursor, List<T> results) {
this.cursor = cursor;
this.results = results;
this.cursor = cursor;
this.results = results;
}
public String getCursor() {
return SafeEncoder.encode(cursor);
return SafeEncoder.encode(cursor);
}
public byte[] getCursorAsBytes() {
return cursor;
return cursor;
}
public List<T> getResult() {
return results;
return results;
}
}

View File

@@ -15,10 +15,10 @@ public interface SentinelCommands {
public String sentinelFailover(String masterName);
public String sentinelMonitor(String masterName, String ip, int port,
int quorum);
int quorum);
public String sentinelRemove(String masterName);
public String sentinelSet(String masterName,
Map<String, String> parameterMap);
Map<String, String> parameterMap);
}

View File

@@ -12,648 +12,648 @@ import redis.clients.util.Hashing;
import redis.clients.util.Pool;
public class ShardedJedis extends BinaryShardedJedis implements JedisCommands,
Closeable {
Closeable {
protected Pool<ShardedJedis> dataSource = null;
public ShardedJedis(List<JedisShardInfo> shards) {
super(shards);
super(shards);
}
public ShardedJedis(List<JedisShardInfo> shards, Hashing algo) {
super(shards, algo);
super(shards, algo);
}
public ShardedJedis(List<JedisShardInfo> shards, Pattern keyTagPattern) {
super(shards, keyTagPattern);
super(shards, keyTagPattern);
}
public ShardedJedis(List<JedisShardInfo> shards, Hashing algo,
Pattern keyTagPattern) {
super(shards, algo, keyTagPattern);
Pattern keyTagPattern) {
super(shards, algo, keyTagPattern);
}
public String set(String key, String value) {
Jedis j = getShard(key);
return j.set(key, value);
Jedis j = getShard(key);
return j.set(key, value);
}
@Override
public String set(String key, String value, String nxxx, String expx,
long time) {
Jedis j = getShard(key);
return j.set(key, value, nxxx, expx, time);
long time) {
Jedis j = getShard(key);
return j.set(key, value, nxxx, expx, time);
}
public String get(String key) {
Jedis j = getShard(key);
return j.get(key);
Jedis j = getShard(key);
return j.get(key);
}
public String echo(String string) {
Jedis j = getShard(string);
return j.echo(string);
Jedis j = getShard(string);
return j.echo(string);
}
public Boolean exists(String key) {
Jedis j = getShard(key);
return j.exists(key);
Jedis j = getShard(key);
return j.exists(key);
}
public String type(String key) {
Jedis j = getShard(key);
return j.type(key);
Jedis j = getShard(key);
return j.type(key);
}
public Long expire(String key, int seconds) {
Jedis j = getShard(key);
return j.expire(key, seconds);
Jedis j = getShard(key);
return j.expire(key, seconds);
}
public Long expireAt(String key, long unixTime) {
Jedis j = getShard(key);
return j.expireAt(key, unixTime);
Jedis j = getShard(key);
return j.expireAt(key, unixTime);
}
public Long ttl(String key) {
Jedis j = getShard(key);
return j.ttl(key);
Jedis j = getShard(key);
return j.ttl(key);
}
public Boolean setbit(String key, long offset, boolean value) {
Jedis j = getShard(key);
return j.setbit(key, offset, value);
Jedis j = getShard(key);
return j.setbit(key, offset, value);
}
public Boolean setbit(String key, long offset, String value) {
Jedis j = getShard(key);
return j.setbit(key, offset, value);
Jedis j = getShard(key);
return j.setbit(key, offset, value);
}
public Boolean getbit(String key, long offset) {
Jedis j = getShard(key);
return j.getbit(key, offset);
Jedis j = getShard(key);
return j.getbit(key, offset);
}
public Long setrange(String key, long offset, String value) {
Jedis j = getShard(key);
return j.setrange(key, offset, value);
Jedis j = getShard(key);
return j.setrange(key, offset, value);
}
public String getrange(String key, long startOffset, long endOffset) {
Jedis j = getShard(key);
return j.getrange(key, startOffset, endOffset);
Jedis j = getShard(key);
return j.getrange(key, startOffset, endOffset);
}
public String getSet(String key, String value) {
Jedis j = getShard(key);
return j.getSet(key, value);
Jedis j = getShard(key);
return j.getSet(key, value);
}
public Long setnx(String key, String value) {
Jedis j = getShard(key);
return j.setnx(key, value);
Jedis j = getShard(key);
return j.setnx(key, value);
}
public String setex(String key, int seconds, String value) {
Jedis j = getShard(key);
return j.setex(key, seconds, value);
Jedis j = getShard(key);
return j.setex(key, seconds, value);
}
public List<String> blpop(String arg) {
Jedis j = getShard(arg);
return j.blpop(arg);
Jedis j = getShard(arg);
return j.blpop(arg);
}
public List<String> blpop(int timeout, String key) {
Jedis j = getShard(key);
return j.blpop(timeout, key);
Jedis j = getShard(key);
return j.blpop(timeout, key);
}
public List<String> brpop(String arg) {
Jedis j = getShard(arg);
return j.brpop(arg);
Jedis j = getShard(arg);
return j.brpop(arg);
}
public List<String> brpop(int timeout, String key) {
Jedis j = getShard(key);
return j.brpop(timeout, key);
Jedis j = getShard(key);
return j.brpop(timeout, key);
}
public Long decrBy(String key, long integer) {
Jedis j = getShard(key);
return j.decrBy(key, integer);
Jedis j = getShard(key);
return j.decrBy(key, integer);
}
public Long decr(String key) {
Jedis j = getShard(key);
return j.decr(key);
Jedis j = getShard(key);
return j.decr(key);
}
public Long incrBy(String key, long integer) {
Jedis j = getShard(key);
return j.incrBy(key, integer);
Jedis j = getShard(key);
return j.incrBy(key, integer);
}
public Double incrByFloat(String key, double integer) {
Jedis j = getShard(key);
return j.incrByFloat(key, integer);
Jedis j = getShard(key);
return j.incrByFloat(key, integer);
}
public Long incr(String key) {
Jedis j = getShard(key);
return j.incr(key);
Jedis j = getShard(key);
return j.incr(key);
}
public Long append(String key, String value) {
Jedis j = getShard(key);
return j.append(key, value);
Jedis j = getShard(key);
return j.append(key, value);
}
public String substr(String key, int start, int end) {
Jedis j = getShard(key);
return j.substr(key, start, end);
Jedis j = getShard(key);
return j.substr(key, start, end);
}
public Long hset(String key, String field, String value) {
Jedis j = getShard(key);
return j.hset(key, field, value);
Jedis j = getShard(key);
return j.hset(key, field, value);
}
public String hget(String key, String field) {
Jedis j = getShard(key);
return j.hget(key, field);
Jedis j = getShard(key);
return j.hget(key, field);
}
public Long hsetnx(String key, String field, String value) {
Jedis j = getShard(key);
return j.hsetnx(key, field, value);
Jedis j = getShard(key);
return j.hsetnx(key, field, value);
}
public String hmset(String key, Map<String, String> hash) {
Jedis j = getShard(key);
return j.hmset(key, hash);
Jedis j = getShard(key);
return j.hmset(key, hash);
}
public List<String> hmget(String key, String... fields) {
Jedis j = getShard(key);
return j.hmget(key, fields);
Jedis j = getShard(key);
return j.hmget(key, fields);
}
public Long hincrBy(String key, String field, long value) {
Jedis j = getShard(key);
return j.hincrBy(key, field, value);
Jedis j = getShard(key);
return j.hincrBy(key, field, value);
}
public Double hincrByFloat(String key, String field, double value) {
Jedis j = getShard(key);
return j.hincrByFloat(key, field, value);
Jedis j = getShard(key);
return j.hincrByFloat(key, field, value);
}
public Boolean hexists(String key, String field) {
Jedis j = getShard(key);
return j.hexists(key, field);
Jedis j = getShard(key);
return j.hexists(key, field);
}
public Long del(String key) {
Jedis j = getShard(key);
return j.del(key);
Jedis j = getShard(key);
return j.del(key);
}
public Long hdel(String key, String... fields) {
Jedis j = getShard(key);
return j.hdel(key, fields);
Jedis j = getShard(key);
return j.hdel(key, fields);
}
public Long hlen(String key) {
Jedis j = getShard(key);
return j.hlen(key);
Jedis j = getShard(key);
return j.hlen(key);
}
public Set<String> hkeys(String key) {
Jedis j = getShard(key);
return j.hkeys(key);
Jedis j = getShard(key);
return j.hkeys(key);
}
public List<String> hvals(String key) {
Jedis j = getShard(key);
return j.hvals(key);
Jedis j = getShard(key);
return j.hvals(key);
}
public Map<String, String> hgetAll(String key) {
Jedis j = getShard(key);
return j.hgetAll(key);
Jedis j = getShard(key);
return j.hgetAll(key);
}
public Long rpush(String key, String... strings) {
Jedis j = getShard(key);
return j.rpush(key, strings);
Jedis j = getShard(key);
return j.rpush(key, strings);
}
public Long lpush(String key, String... strings) {
Jedis j = getShard(key);
return j.lpush(key, strings);
Jedis j = getShard(key);
return j.lpush(key, strings);
}
public Long lpushx(String key, String... string) {
Jedis j = getShard(key);
return j.lpushx(key, string);
Jedis j = getShard(key);
return j.lpushx(key, string);
}
public Long strlen(final String key) {
Jedis j = getShard(key);
return j.strlen(key);
Jedis j = getShard(key);
return j.strlen(key);
}
public Long move(String key, int dbIndex) {
Jedis j = getShard(key);
return j.move(key, dbIndex);
Jedis j = getShard(key);
return j.move(key, dbIndex);
}
public Long rpushx(String key, String... string) {
Jedis j = getShard(key);
return j.rpushx(key, string);
Jedis j = getShard(key);
return j.rpushx(key, string);
}
public Long persist(final String key) {
Jedis j = getShard(key);
return j.persist(key);
Jedis j = getShard(key);
return j.persist(key);
}
public Long llen(String key) {
Jedis j = getShard(key);
return j.llen(key);
Jedis j = getShard(key);
return j.llen(key);
}
public List<String> lrange(String key, long start, long end) {
Jedis j = getShard(key);
return j.lrange(key, start, end);
Jedis j = getShard(key);
return j.lrange(key, start, end);
}
public String ltrim(String key, long start, long end) {
Jedis j = getShard(key);
return j.ltrim(key, start, end);
Jedis j = getShard(key);
return j.ltrim(key, start, end);
}
public String lindex(String key, long index) {
Jedis j = getShard(key);
return j.lindex(key, index);
Jedis j = getShard(key);
return j.lindex(key, index);
}
public String lset(String key, long index, String value) {
Jedis j = getShard(key);
return j.lset(key, index, value);
Jedis j = getShard(key);
return j.lset(key, index, value);
}
public Long lrem(String key, long count, String value) {
Jedis j = getShard(key);
return j.lrem(key, count, value);
Jedis j = getShard(key);
return j.lrem(key, count, value);
}
public String lpop(String key) {
Jedis j = getShard(key);
return j.lpop(key);
Jedis j = getShard(key);
return j.lpop(key);
}
public String rpop(String key) {
Jedis j = getShard(key);
return j.rpop(key);
Jedis j = getShard(key);
return j.rpop(key);
}
public Long sadd(String key, String... members) {
Jedis j = getShard(key);
return j.sadd(key, members);
Jedis j = getShard(key);
return j.sadd(key, members);
}
public Set<String> smembers(String key) {
Jedis j = getShard(key);
return j.smembers(key);
Jedis j = getShard(key);
return j.smembers(key);
}
public Long srem(String key, String... members) {
Jedis j = getShard(key);
return j.srem(key, members);
Jedis j = getShard(key);
return j.srem(key, members);
}
public String spop(String key) {
Jedis j = getShard(key);
return j.spop(key);
Jedis j = getShard(key);
return j.spop(key);
}
public Long scard(String key) {
Jedis j = getShard(key);
return j.scard(key);
Jedis j = getShard(key);
return j.scard(key);
}
public Boolean sismember(String key, String member) {
Jedis j = getShard(key);
return j.sismember(key, member);
Jedis j = getShard(key);
return j.sismember(key, member);
}
public String srandmember(String key) {
Jedis j = getShard(key);
return j.srandmember(key);
Jedis j = getShard(key);
return j.srandmember(key);
}
@Override
public List<String> srandmember(String key, int count) {
Jedis j = getShard(key);
return j.srandmember(key, count);
Jedis j = getShard(key);
return j.srandmember(key, count);
}
public Long zadd(String key, double score, String member) {
Jedis j = getShard(key);
return j.zadd(key, score, member);
Jedis j = getShard(key);
return j.zadd(key, score, member);
}
public Long zadd(String key, Map<String, Double> scoreMembers) {
Jedis j = getShard(key);
return j.zadd(key, scoreMembers);
Jedis j = getShard(key);
return j.zadd(key, scoreMembers);
}
public Set<String> zrange(String key, long start, long end) {
Jedis j = getShard(key);
return j.zrange(key, start, end);
Jedis j = getShard(key);
return j.zrange(key, start, end);
}
public Long zrem(String key, String... members) {
Jedis j = getShard(key);
return j.zrem(key, members);
Jedis j = getShard(key);
return j.zrem(key, members);
}
public Double zincrby(String key, double score, String member) {
Jedis j = getShard(key);
return j.zincrby(key, score, member);
Jedis j = getShard(key);
return j.zincrby(key, score, member);
}
public Long zrank(String key, String member) {
Jedis j = getShard(key);
return j.zrank(key, member);
Jedis j = getShard(key);
return j.zrank(key, member);
}
public Long zrevrank(String key, String member) {
Jedis j = getShard(key);
return j.zrevrank(key, member);
Jedis j = getShard(key);
return j.zrevrank(key, member);
}
public Set<String> zrevrange(String key, long start, long end) {
Jedis j = getShard(key);
return j.zrevrange(key, start, end);
Jedis j = getShard(key);
return j.zrevrange(key, start, end);
}
public Set<Tuple> zrangeWithScores(String key, long start, long end) {
Jedis j = getShard(key);
return j.zrangeWithScores(key, start, end);
Jedis j = getShard(key);
return j.zrangeWithScores(key, start, end);
}
public Set<Tuple> zrevrangeWithScores(String key, long start, long end) {
Jedis j = getShard(key);
return j.zrevrangeWithScores(key, start, end);
Jedis j = getShard(key);
return j.zrevrangeWithScores(key, start, end);
}
public Long zcard(String key) {
Jedis j = getShard(key);
return j.zcard(key);
Jedis j = getShard(key);
return j.zcard(key);
}
public Double zscore(String key, String member) {
Jedis j = getShard(key);
return j.zscore(key, member);
Jedis j = getShard(key);
return j.zscore(key, member);
}
public List<String> sort(String key) {
Jedis j = getShard(key);
return j.sort(key);
Jedis j = getShard(key);
return j.sort(key);
}
public List<String> sort(String key, SortingParams sortingParameters) {
Jedis j = getShard(key);
return j.sort(key, sortingParameters);
Jedis j = getShard(key);
return j.sort(key, sortingParameters);
}
public Long zcount(String key, double min, double max) {
Jedis j = getShard(key);
return j.zcount(key, min, max);
Jedis j = getShard(key);
return j.zcount(key, min, max);
}
public Long zcount(String key, String min, String max) {
Jedis j = getShard(key);
return j.zcount(key, min, max);
Jedis j = getShard(key);
return j.zcount(key, min, max);
}
public Set<String> zrangeByScore(String key, double min, double max) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max);
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max);
}
public Set<String> zrevrangeByScore(String key, double max, double min) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min);
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min);
}
public Set<String> zrangeByScore(String key, double min, double max,
int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count);
int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count);
}
public Set<String> zrevrangeByScore(String key, double max, double min,
int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count);
int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count);
}
public Set<Tuple> zrangeByScoreWithScores(String key, double min, double max) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max);
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max);
}
public Set<Tuple> zrevrangeByScoreWithScores(String key, double max,
double min) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min);
double min) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min);
}
public Set<Tuple> zrangeByScoreWithScores(String key, double min,
double max, int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count);
double max, int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count);
}
public Set<Tuple> zrevrangeByScoreWithScores(String key, double max,
double min, int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
double min, int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
}
public Set<String> zrangeByScore(String key, String min, String max) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max);
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max);
}
public Set<String> zrevrangeByScore(String key, String max, String min) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min);
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min);
}
public Set<String> zrangeByScore(String key, String min, String max,
int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count);
int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count);
}
public Set<String> zrevrangeByScore(String key, String max, String min,
int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count);
int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count);
}
public Set<Tuple> zrangeByScoreWithScores(String key, String min, String max) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max);
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max);
}
public Set<Tuple> zrevrangeByScoreWithScores(String key, String max,
String min) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min);
String min) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min);
}
public Set<Tuple> zrangeByScoreWithScores(String key, String min,
String max, int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count);
String max, int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count);
}
public Set<Tuple> zrevrangeByScoreWithScores(String key, String max,
String min, int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
String min, int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
}
public Long zremrangeByRank(String key, long start, long end) {
Jedis j = getShard(key);
return j.zremrangeByRank(key, start, end);
Jedis j = getShard(key);
return j.zremrangeByRank(key, start, end);
}
public Long zremrangeByScore(String key, double start, double end) {
Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end);
Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end);
}
public Long zremrangeByScore(String key, String start, String end) {
Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end);
Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end);
}
@Override
public Long zlexcount(final String key, final String min, final String max) {
return getShard(key).zlexcount(key, min, max);
return getShard(key).zlexcount(key, min, max);
}
@Override
public Set<String> zrangeByLex(final String key, final String min,
final String max) {
return getShard(key).zrangeByLex(key, min, max);
final String max) {
return getShard(key).zrangeByLex(key, min, max);
}
@Override
public Set<String> zrangeByLex(final String key, final String min,
final String max, final int offset, final int count) {
return getShard(key).zrangeByLex(key, min, max, offset, count);
final String max, final int offset, final int count) {
return getShard(key).zrangeByLex(key, min, max, offset, count);
}
@Override
public Set<String> zrevrangeByLex(String key, String max, String min) {
return getShard(key).zrevrangeByLex(key, max, min);
return getShard(key).zrevrangeByLex(key, max, min);
}
@Override
public Set<String> zrevrangeByLex(String key, String max, String min,
int offset, int count) {
return getShard(key).zrevrangeByLex(key, max, min, offset, count);
int offset, int count) {
return getShard(key).zrevrangeByLex(key, max, min, offset, count);
}
@Override
public Long zremrangeByLex(final String key, final String min,
final String max) {
return getShard(key).zremrangeByLex(key, min, max);
final String max) {
return getShard(key).zremrangeByLex(key, min, max);
}
public Long linsert(String key, LIST_POSITION where, String pivot,
String value) {
Jedis j = getShard(key);
return j.linsert(key, where, pivot, value);
String value) {
Jedis j = getShard(key);
return j.linsert(key, where, pivot, value);
}
public Long bitcount(final String key) {
Jedis j = getShard(key);
return j.bitcount(key);
Jedis j = getShard(key);
return j.bitcount(key);
}
public Long bitcount(final String key, long start, long end) {
Jedis j = getShard(key);
return j.bitcount(key, start, end);
Jedis j = getShard(key);
return j.bitcount(key, start, end);
}
public ScanResult<Entry<String, String>> hscan(String key,
final String cursor) {
Jedis j = getShard(key);
return j.hscan(key, cursor);
final String cursor) {
Jedis j = getShard(key);
return j.hscan(key, cursor);
}
public ScanResult<String> sscan(String key, final String cursor) {
Jedis j = getShard(key);
return j.sscan(key, cursor);
Jedis j = getShard(key);
return j.sscan(key, cursor);
}
public ScanResult<Tuple> zscan(String key, final String cursor) {
Jedis j = getShard(key);
return j.zscan(key, cursor);
Jedis j = getShard(key);
return j.zscan(key, cursor);
}
@Override
public void close() {
if (dataSource != null) {
boolean broken = false;
if (dataSource != null) {
boolean broken = false;
for (Jedis jedis : getAllShards()) {
if (jedis.getClient().isBroken()) {
broken = true;
}
}
for (Jedis jedis : getAllShards()) {
if (jedis.getClient().isBroken()) {
broken = true;
}
}
if (broken) {
dataSource.returnBrokenResource(this);
} else {
this.resetState();
dataSource.returnResource(this);
}
if (broken) {
dataSource.returnBrokenResource(this);
} else {
this.resetState();
dataSource.returnResource(this);
}
} else {
disconnect();
}
} else {
disconnect();
}
}
public void setDataSource(Pool<ShardedJedis> shardedJedisPool) {
this.dataSource = shardedJedisPool;
this.dataSource = shardedJedisPool;
}
public void resetState() {
for (Jedis jedis : getAllShards()) {
jedis.resetState();
}
for (Jedis jedis : getAllShards()) {
jedis.resetState();
}
}
public Long pfadd(String key, String... elements) {
Jedis j = getShard(key);
return j.pfadd(key, elements);
Jedis j = getShard(key);
return j.pfadd(key, elements);
}
@Override
public long pfcount(String key) {
Jedis j = getShard(key);
return j.pfcount(key);
Jedis j = getShard(key);
return j.pfcount(key);
}
}

View File

@@ -11,27 +11,27 @@ public class ShardedJedisPipeline extends PipelineBase {
private Queue<Client> clients = new LinkedList<Client>();
private static class FutureResult {
private Client client;
private Client client;
public FutureResult(Client client) {
this.client = client;
}
public FutureResult(Client client) {
this.client = client;
}
public Object get() {
return client.getOne();
}
public Object get() {
return client.getOne();
}
}
public void setShardedJedis(BinaryShardedJedis jedis) {
this.jedis = jedis;
this.jedis = jedis;
}
public List<Object> getResults() {
List<Object> r = new ArrayList<Object>();
for (FutureResult fr : results) {
r.add(fr.get());
}
return r;
List<Object> r = new ArrayList<Object>();
for (FutureResult fr : results) {
r.add(fr.get());
}
return r;
}
/**
@@ -40,9 +40,9 @@ public class ShardedJedisPipeline extends PipelineBase {
* the different Response&lt;?&gt; of the commands you execute.
*/
public void sync() {
for (Client client : clients) {
generateResponse(client.getOne());
}
for (Client client : clients) {
generateResponse(client.getOne());
}
}
/**
@@ -54,26 +54,26 @@ public class ShardedJedisPipeline extends PipelineBase {
* @return A list of all the responses in the order you executed them.
*/
public List<Object> syncAndReturnAll() {
List<Object> formatted = new ArrayList<Object>();
for (Client client : clients) {
formatted.add(generateResponse(client.getOne()).get());
}
return formatted;
List<Object> formatted = new ArrayList<Object>();
for (Client client : clients) {
formatted.add(generateResponse(client.getOne()).get());
}
return formatted;
}
@Override
protected Client getClient(String key) {
Client client = jedis.getShard(key).getClient();
clients.add(client);
results.add(new FutureResult(client));
return client;
Client client = jedis.getShard(key).getClient();
clients.add(client);
results.add(new FutureResult(client));
return client;
}
@Override
protected Client getClient(byte[] key) {
Client client = jedis.getShard(key).getClient();
clients.add(client);
results.add(new FutureResult(client));
return client;
Client client = jedis.getShard(key).getClient();
clients.add(client);
results.add(new FutureResult(client));
return client;
}
}

View File

@@ -13,113 +13,113 @@ import redis.clients.util.Pool;
public class ShardedJedisPool extends Pool<ShardedJedis> {
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,
List<JedisShardInfo> shards) {
this(poolConfig, shards, Hashing.MURMUR_HASH);
List<JedisShardInfo> shards) {
this(poolConfig, shards, Hashing.MURMUR_HASH);
}
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,
List<JedisShardInfo> shards, Hashing algo) {
this(poolConfig, shards, algo, null);
List<JedisShardInfo> shards, Hashing algo) {
this(poolConfig, shards, algo, null);
}
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,
List<JedisShardInfo> shards, Pattern keyTagPattern) {
this(poolConfig, shards, Hashing.MURMUR_HASH, keyTagPattern);
List<JedisShardInfo> shards, Pattern keyTagPattern) {
this(poolConfig, shards, Hashing.MURMUR_HASH, keyTagPattern);
}
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,
List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) {
super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern));
List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) {
super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern));
}
@Override
public ShardedJedis getResource() {
ShardedJedis jedis = super.getResource();
jedis.setDataSource(this);
return jedis;
ShardedJedis jedis = super.getResource();
jedis.setDataSource(this);
return jedis;
}
@Override
public void returnBrokenResource(final ShardedJedis resource) {
if (resource != null) {
returnBrokenResourceObject(resource);
}
if (resource != null) {
returnBrokenResourceObject(resource);
}
}
@Override
public void returnResource(final ShardedJedis resource) {
if (resource != null) {
resource.resetState();
returnResourceObject(resource);
}
if (resource != null) {
resource.resetState();
returnResourceObject(resource);
}
}
/**
* PoolableObjectFactory custom impl.
*/
private static class ShardedJedisFactory implements
PooledObjectFactory<ShardedJedis> {
private List<JedisShardInfo> shards;
private Hashing algo;
private Pattern keyTagPattern;
PooledObjectFactory<ShardedJedis> {
private List<JedisShardInfo> shards;
private Hashing algo;
private Pattern keyTagPattern;
public ShardedJedisFactory(List<JedisShardInfo> shards, Hashing algo,
Pattern keyTagPattern) {
this.shards = shards;
this.algo = algo;
this.keyTagPattern = keyTagPattern;
}
public ShardedJedisFactory(List<JedisShardInfo> shards, Hashing algo,
Pattern keyTagPattern) {
this.shards = shards;
this.algo = algo;
this.keyTagPattern = keyTagPattern;
}
@Override
public PooledObject<ShardedJedis> makeObject() throws Exception {
ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern);
return new DefaultPooledObject<ShardedJedis>(jedis);
}
@Override
public PooledObject<ShardedJedis> makeObject() throws Exception {
ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern);
return new DefaultPooledObject<ShardedJedis>(jedis);
}
@Override
public void destroyObject(PooledObject<ShardedJedis> pooledShardedJedis)
throws Exception {
final ShardedJedis shardedJedis = pooledShardedJedis.getObject();
for (Jedis jedis : shardedJedis.getAllShards()) {
try {
try {
jedis.quit();
} catch (Exception e) {
@Override
public void destroyObject(PooledObject<ShardedJedis> pooledShardedJedis)
throws Exception {
final ShardedJedis shardedJedis = pooledShardedJedis.getObject();
for (Jedis jedis : shardedJedis.getAllShards()) {
try {
try {
jedis.quit();
} catch (Exception e) {
}
jedis.disconnect();
} catch (Exception e) {
}
jedis.disconnect();
} catch (Exception e) {
}
}
}
}
}
}
@Override
public boolean validateObject(
PooledObject<ShardedJedis> pooledShardedJedis) {
try {
ShardedJedis jedis = pooledShardedJedis.getObject();
for (Jedis shard : jedis.getAllShards()) {
if (!shard.ping().equals("PONG")) {
return false;
}
}
return true;
} catch (Exception ex) {
return false;
}
}
@Override
public boolean validateObject(
PooledObject<ShardedJedis> pooledShardedJedis) {
try {
ShardedJedis jedis = pooledShardedJedis.getObject();
for (Jedis shard : jedis.getAllShards()) {
if (!shard.ping().equals("PONG")) {
return false;
}
}
return true;
} catch (Exception ex) {
return false;
}
}
@Override
public void activateObject(PooledObject<ShardedJedis> p)
throws Exception {
@Override
public void activateObject(PooledObject<ShardedJedis> p)
throws Exception {
}
}
@Override
public void passivateObject(PooledObject<ShardedJedis> p)
throws Exception {
@Override
public void passivateObject(PooledObject<ShardedJedis> p)
throws Exception {
}
}
}
}

View File

@@ -36,7 +36,7 @@ public class SortingParams {
* @return the SortingParams Object
*/
public SortingParams by(final String pattern) {
return by(SafeEncoder.encode(pattern));
return by(SafeEncoder.encode(pattern));
}
/**
@@ -53,9 +53,9 @@ public class SortingParams {
* @return the SortingParams Object
*/
public SortingParams by(final byte[] pattern) {
params.add(BY.raw);
params.add(pattern);
return this;
params.add(BY.raw);
params.add(pattern);
return this;
}
/**
@@ -67,13 +67,13 @@ public class SortingParams {
* @return the SortingParams Object
*/
public SortingParams nosort() {
params.add(BY.raw);
params.add(NOSORT.raw);
return this;
params.add(BY.raw);
params.add(NOSORT.raw);
return this;
}
public Collection<byte[]> getParams() {
return Collections.unmodifiableCollection(params);
return Collections.unmodifiableCollection(params);
}
/**
@@ -82,8 +82,8 @@ public class SortingParams {
* @return the sortingParams Object
*/
public SortingParams desc() {
params.add(DESC.raw);
return this;
params.add(DESC.raw);
return this;
}
/**
@@ -92,8 +92,8 @@ public class SortingParams {
* @return the SortingParams Object
*/
public SortingParams asc() {
params.add(ASC.raw);
return this;
params.add(ASC.raw);
return this;
}
/**
@@ -105,10 +105,10 @@ public class SortingParams {
* @return the SortingParams Object
*/
public SortingParams limit(final int start, final int count) {
params.add(LIMIT.raw);
params.add(Protocol.toByteArray(start));
params.add(Protocol.toByteArray(count));
return this;
params.add(LIMIT.raw);
params.add(Protocol.toByteArray(start));
params.add(Protocol.toByteArray(count));
return this;
}
/**
@@ -118,8 +118,8 @@ public class SortingParams {
* @return the SortingParams Object
*/
public SortingParams alpha() {
params.add(ALPHA.raw);
return this;
params.add(ALPHA.raw);
return this;
}
/**
@@ -138,11 +138,11 @@ public class SortingParams {
* @return the SortingParams Object
*/
public SortingParams get(String... patterns) {
for (final String pattern : patterns) {
params.add(GET.raw);
params.add(SafeEncoder.encode(pattern));
}
return this;
for (final String pattern : patterns) {
params.add(GET.raw);
params.add(SafeEncoder.encode(pattern));
}
return this;
}
/**
@@ -161,10 +161,10 @@ public class SortingParams {
* @return the SortingParams Object
*/
public SortingParams get(byte[]... patterns) {
for (final byte[] pattern : patterns) {
params.add(GET.raw);
params.add(pattern);
}
return this;
for (final byte[] pattern : patterns) {
params.add(GET.raw);
params.add(pattern);
}
return this;
}
}

View File

@@ -14,75 +14,75 @@ public class Transaction extends MultiKeyPipelineBase {
protected boolean inTransaction = true;
protected Transaction() {
// client will be set later in transaction block
// client will be set later in transaction block
}
public Transaction(final Client client) {
this.client = client;
this.client = client;
}
@Override
protected Client getClient(String key) {
return client;
return client;
}
@Override
protected Client getClient(byte[] key) {
return client;
return client;
}
public void clear() {
if (inTransaction) {
discard();
}
if (inTransaction) {
discard();
}
}
public List<Object> exec() {
// Discard QUEUED or ERROR
client.getMany(getPipelinedResponseLength());
client.exec();
// Discard QUEUED or ERROR
client.getMany(getPipelinedResponseLength());
client.exec();
List<Object> unformatted = client.getObjectMultiBulkReply();
if (unformatted == null) {
return null;
}
List<Object> formatted = new ArrayList<Object>();
for (Object o : unformatted) {
try {
formatted.add(generateResponse(o).get());
} catch (JedisDataException e) {
formatted.add(e);
}
}
return formatted;
List<Object> unformatted = client.getObjectMultiBulkReply();
if (unformatted == null) {
return null;
}
List<Object> formatted = new ArrayList<Object>();
for (Object o : unformatted) {
try {
formatted.add(generateResponse(o).get());
} catch (JedisDataException e) {
formatted.add(e);
}
}
return formatted;
}
public List<Response<?>> execGetResponse() {
// Discard QUEUED or ERROR
client.getMany(getPipelinedResponseLength());
client.exec();
// Discard QUEUED or ERROR
client.getMany(getPipelinedResponseLength());
client.exec();
List<Object> unformatted = client.getObjectMultiBulkReply();
if (unformatted == null) {
return null;
}
List<Response<?>> response = new ArrayList<Response<?>>();
for (Object o : unformatted) {
response.add(generateResponse(o));
}
return response;
List<Object> unformatted = client.getObjectMultiBulkReply();
if (unformatted == null) {
return null;
}
List<Response<?>> response = new ArrayList<Response<?>>();
for (Object o : unformatted) {
response.add(generateResponse(o));
}
return response;
}
public String discard() {
client.getMany(getPipelinedResponseLength());
client.discard();
inTransaction = false;
clean();
return client.getStatusCodeReply();
client.getMany(getPipelinedResponseLength());
client.discard();
inTransaction = false;
clean();
return client.getStatusCodeReply();
}
public void setClient(Client client) {
this.client = client;
this.client = client;
}
}

View File

@@ -9,72 +9,72 @@ public class Tuple implements Comparable<Tuple> {
private Double score;
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result;
if (null != element) {
for (final byte b : element) {
result = prime * result + b;
}
}
long temp;
temp = Double.doubleToLongBits(score);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
final int prime = 31;
int result = 1;
result = prime * result;
if (null != element) {
for (final byte b : element) {
result = prime * result + b;
}
}
long temp;
temp = Double.doubleToLongBits(score);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tuple other = (Tuple) obj;
if (element == null) {
if (other.element != null)
return false;
} else if (!Arrays.equals(element, other.element))
return false;
return true;
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tuple other = (Tuple) obj;
if (element == null) {
if (other.element != null)
return false;
} else if (!Arrays.equals(element, other.element))
return false;
return true;
}
public int compareTo(Tuple other) {
if (Arrays.equals(this.element, other.element))
return 0;
else
return this.score < other.getScore() ? -1 : 1;
if (Arrays.equals(this.element, other.element))
return 0;
else
return this.score < other.getScore() ? -1 : 1;
}
public Tuple(String element, Double score) {
super();
this.element = SafeEncoder.encode(element);
this.score = score;
super();
this.element = SafeEncoder.encode(element);
this.score = score;
}
public Tuple(byte[] element, Double score) {
super();
this.element = element;
this.score = score;
super();
this.element = element;
this.score = score;
}
public String getElement() {
if (null != element) {
return SafeEncoder.encode(element);
} else {
return null;
}
if (null != element) {
return SafeEncoder.encode(element);
} else {
return null;
}
}
public byte[] getBinaryElement() {
return element;
return element;
}
public double getScore() {
return score;
return score;
}
public String toString() {
return '[' + Arrays.toString(element) + ',' + score + ']';
return '[' + Arrays.toString(element) + ',' + score + ']';
}
}

View File

@@ -12,13 +12,13 @@ import redis.clients.util.SafeEncoder;
public class ZParams {
public enum Aggregate {
SUM, MIN, MAX;
SUM, MIN, MAX;
public final byte[] raw;
public final byte[] raw;
Aggregate() {
raw = SafeEncoder.encode(name());
}
Aggregate() {
raw = SafeEncoder.encode(name());
}
}
private List<byte[]> params = new ArrayList<byte[]>();
@@ -30,21 +30,21 @@ public class ZParams {
* weights.
*/
public ZParams weights(final double... weights) {
params.add(WEIGHTS.raw);
for (final double weight : weights) {
params.add(Protocol.toByteArray(weight));
}
params.add(WEIGHTS.raw);
for (final double weight : weights) {
params.add(Protocol.toByteArray(weight));
}
return this;
return this;
}
public Collection<byte[]> getParams() {
return Collections.unmodifiableCollection(params);
return Collections.unmodifiableCollection(params);
}
public ZParams aggregate(final Aggregate aggregate) {
params.add(AGGREGATE.raw);
params.add(aggregate.raw);
return this;
params.add(AGGREGATE.raw);
params.add(aggregate.raw);
return this;
}
}

View File

@@ -6,18 +6,18 @@ public class JedisAskDataException extends JedisRedirectionException {
private static final long serialVersionUID = 3878126572474819403L;
public JedisAskDataException(Throwable cause, HostAndPort targetHost,
int slot) {
super(cause, targetHost, slot);
int slot) {
super(cause, targetHost, slot);
}
public JedisAskDataException(String message, Throwable cause,
HostAndPort targetHost, int slot) {
super(message, cause, targetHost, slot);
HostAndPort targetHost, int slot) {
super(message, cause, targetHost, slot);
}
public JedisAskDataException(String message, HostAndPort targetHost,
int slot) {
super(message, targetHost, slot);
int slot) {
super(message, targetHost, slot);
}
}

View File

@@ -4,14 +4,14 @@ public class JedisClusterException extends JedisDataException {
private static final long serialVersionUID = 3878126572474819403L;
public JedisClusterException(Throwable cause) {
super(cause);
super(cause);
}
public JedisClusterException(String message, Throwable cause) {
super(message, cause);
super(message, cause);
}
public JedisClusterException(String message) {
super(message);
super(message);
}
}

View File

@@ -4,14 +4,14 @@ public class JedisClusterMaxRedirectionsException extends JedisDataException {
private static final long serialVersionUID = 3878126572474819403L;
public JedisClusterMaxRedirectionsException(Throwable cause) {
super(cause);
super(cause);
}
public JedisClusterMaxRedirectionsException(String message, Throwable cause) {
super(message, cause);
super(message, cause);
}
public JedisClusterMaxRedirectionsException(String message) {
super(message);
super(message);
}
}

View File

@@ -4,14 +4,14 @@ public class JedisConnectionException extends JedisException {
private static final long serialVersionUID = 3878126572474819403L;
public JedisConnectionException(String message) {
super(message);
super(message);
}
public JedisConnectionException(Throwable cause) {
super(cause);
super(cause);
}
public JedisConnectionException(String message, Throwable cause) {
super(message, cause);
super(message, cause);
}
}

View File

@@ -4,14 +4,14 @@ public class JedisDataException extends JedisException {
private static final long serialVersionUID = 3878126572474819403L;
public JedisDataException(String message) {
super(message);
super(message);
}
public JedisDataException(Throwable cause) {
super(cause);
super(cause);
}
public JedisDataException(String message, Throwable cause) {
super(message, cause);
super(message, cause);
}
}

View File

@@ -4,14 +4,14 @@ public class JedisException extends RuntimeException {
private static final long serialVersionUID = -2946266495682282677L;
public JedisException(String message) {
super(message);
super(message);
}
public JedisException(Throwable e) {
super(e);
super(e);
}
public JedisException(String message, Throwable cause) {
super(message, cause);
super(message, cause);
}
}

View File

@@ -6,17 +6,17 @@ public class JedisMovedDataException extends JedisRedirectionException {
private static final long serialVersionUID = 3878126572474819403L;
public JedisMovedDataException(String message, HostAndPort targetNode,
int slot) {
super(message, targetNode, slot);
int slot) {
super(message, targetNode, slot);
}
public JedisMovedDataException(Throwable cause, HostAndPort targetNode,
int slot) {
super(cause, targetNode, slot);
int slot) {
super(cause, targetNode, slot);
}
public JedisMovedDataException(String message, Throwable cause,
HostAndPort targetNode, int slot) {
super(message, cause, targetNode, slot);
HostAndPort targetNode, int slot) {
super(message, cause, targetNode, slot);
}
}

View File

@@ -9,31 +9,31 @@ public class JedisRedirectionException extends JedisDataException {
private int slot;
public JedisRedirectionException(String message, HostAndPort targetNode,
int slot) {
super(message);
this.targetNode = targetNode;
this.slot = slot;
int slot) {
super(message);
this.targetNode = targetNode;
this.slot = slot;
}
public JedisRedirectionException(Throwable cause, HostAndPort targetNode,
int slot) {
super(cause);
this.targetNode = targetNode;
this.slot = slot;
int slot) {
super(cause);
this.targetNode = targetNode;
this.slot = slot;
}
public JedisRedirectionException(String message, Throwable cause,
HostAndPort targetNode, int slot) {
super(message, cause);
this.targetNode = targetNode;
this.slot = slot;
HostAndPort targetNode, int slot) {
super(message, cause);
this.targetNode = targetNode;
this.slot = slot;
}
public HostAndPort getTargetNode() {
return targetNode;
return targetNode;
}
public int getSlot() {
return slot;
return slot;
}
}

View File

@@ -12,37 +12,37 @@ public class ClusterNodeInformation {
private List<Integer> slotsBeingMigrated;
public ClusterNodeInformation(HostAndPort node) {
this.node = node;
this.availableSlots = new ArrayList<Integer>();
this.slotsBeingImported = new ArrayList<Integer>();
this.slotsBeingMigrated = new ArrayList<Integer>();
this.node = node;
this.availableSlots = new ArrayList<Integer>();
this.slotsBeingImported = new ArrayList<Integer>();
this.slotsBeingMigrated = new ArrayList<Integer>();
}
public void addAvailableSlot(int slot) {
availableSlots.add(slot);
availableSlots.add(slot);
}
public void addSlotBeingImported(int slot) {
slotsBeingImported.add(slot);
slotsBeingImported.add(slot);
}
public void addSlotBeingMigrated(int slot) {
slotsBeingMigrated.add(slot);
slotsBeingMigrated.add(slot);
}
public HostAndPort getNode() {
return node;
return node;
}
public List<Integer> getAvailableSlots() {
return availableSlots;
return availableSlots;
}
public List<Integer> getSlotsBeingImported() {
return slotsBeingImported;
return slotsBeingImported;
}
public List<Integer> getSlotsBeingMigrated() {
return slotsBeingMigrated;
return slotsBeingMigrated;
}
}

View File

@@ -9,72 +9,72 @@ public class ClusterNodeInformationParser {
public static final int HOST_AND_PORT_INDEX = 1;
public ClusterNodeInformation parse(String nodeInfo, HostAndPort current) {
String[] nodeInfoPartArray = nodeInfo.split(" ");
String[] nodeInfoPartArray = nodeInfo.split(" ");
HostAndPort node = getHostAndPortFromNodeLine(nodeInfoPartArray,
current);
ClusterNodeInformation info = new ClusterNodeInformation(node);
HostAndPort node = getHostAndPortFromNodeLine(nodeInfoPartArray,
current);
ClusterNodeInformation info = new ClusterNodeInformation(node);
if (nodeInfoPartArray.length >= SLOT_INFORMATIONS_START_INDEX) {
String[] slotInfoPartArray = extractSlotParts(nodeInfoPartArray);
fillSlotInformation(slotInfoPartArray, info);
}
if (nodeInfoPartArray.length >= SLOT_INFORMATIONS_START_INDEX) {
String[] slotInfoPartArray = extractSlotParts(nodeInfoPartArray);
fillSlotInformation(slotInfoPartArray, info);
}
return info;
return info;
}
private String[] extractSlotParts(String[] nodeInfoPartArray) {
String[] slotInfoPartArray = new String[nodeInfoPartArray.length
- SLOT_INFORMATIONS_START_INDEX];
for (int i = SLOT_INFORMATIONS_START_INDEX; i < nodeInfoPartArray.length; i++) {
slotInfoPartArray[i - SLOT_INFORMATIONS_START_INDEX] = nodeInfoPartArray[i];
}
return slotInfoPartArray;
String[] slotInfoPartArray = new String[nodeInfoPartArray.length
- SLOT_INFORMATIONS_START_INDEX];
for (int i = SLOT_INFORMATIONS_START_INDEX; i < nodeInfoPartArray.length; i++) {
slotInfoPartArray[i - SLOT_INFORMATIONS_START_INDEX] = nodeInfoPartArray[i];
}
return slotInfoPartArray;
}
public HostAndPort getHostAndPortFromNodeLine(String[] nodeInfoPartArray,
HostAndPort current) {
String stringHostAndPort = nodeInfoPartArray[HOST_AND_PORT_INDEX];
HostAndPort current) {
String stringHostAndPort = nodeInfoPartArray[HOST_AND_PORT_INDEX];
String[] arrayHostAndPort = stringHostAndPort.split(":");
return new HostAndPort(
arrayHostAndPort[0].isEmpty() ? current.getHost()
: arrayHostAndPort[0],
arrayHostAndPort[1].isEmpty() ? current.getPort() : Integer
.valueOf(arrayHostAndPort[1]));
String[] arrayHostAndPort = stringHostAndPort.split(":");
return new HostAndPort(
arrayHostAndPort[0].isEmpty() ? current.getHost()
: arrayHostAndPort[0],
arrayHostAndPort[1].isEmpty() ? current.getPort() : Integer
.valueOf(arrayHostAndPort[1]));
}
private void fillSlotInformation(String[] slotInfoPartArray,
ClusterNodeInformation info) {
for (String slotRange : slotInfoPartArray) {
fillSlotInformationFromSlotRange(slotRange, info);
}
ClusterNodeInformation info) {
for (String slotRange : slotInfoPartArray) {
fillSlotInformationFromSlotRange(slotRange, info);
}
}
private void fillSlotInformationFromSlotRange(String slotRange,
ClusterNodeInformation info) {
if (slotRange.startsWith(SLOT_IN_TRANSITION_IDENTIFIER)) {
// slot is in transition
int slot = Integer.parseInt(slotRange.substring(1).split("-")[0]);
ClusterNodeInformation info) {
if (slotRange.startsWith(SLOT_IN_TRANSITION_IDENTIFIER)) {
// slot is in transition
int slot = Integer.parseInt(slotRange.substring(1).split("-")[0]);
if (slotRange.contains(SLOT_IMPORT_IDENTIFIER)) {
// import
info.addSlotBeingImported(slot);
} else {
// migrate (->-)
info.addSlotBeingMigrated(slot);
}
} else if (slotRange.contains("-")) {
// slot range
String[] slotRangePart = slotRange.split("-");
for (int slot = Integer.valueOf(slotRangePart[0]); slot <= Integer
.valueOf(slotRangePart[1]); slot++) {
info.addAvailableSlot(slot);
}
} else {
// single slot
info.addAvailableSlot(Integer.valueOf(slotRange));
}
if (slotRange.contains(SLOT_IMPORT_IDENTIFIER)) {
// import
info.addSlotBeingImported(slot);
} else {
// migrate (->-)
info.addSlotBeingMigrated(slot);
}
} else if (slotRange.contains("-")) {
// slot range
String[] slotRangePart = slotRange.split("-");
for (int slot = Integer.valueOf(slotRangePart[0]); slot <= Integer
.valueOf(slotRangePart[1]); slot++) {
info.addAvailableSlot(slot);
}
} else {
// single slot
info.addAvailableSlot(Integer.valueOf(slotRange));
}
}
}

View File

@@ -8,28 +8,28 @@ public interface Hashing {
public ThreadLocal<MessageDigest> md5Holder = new ThreadLocal<MessageDigest>();
public static final Hashing MD5 = new Hashing() {
public long hash(String key) {
return hash(SafeEncoder.encode(key));
}
public long hash(String key) {
return hash(SafeEncoder.encode(key));
}
public long hash(byte[] key) {
try {
if (md5Holder.get() == null) {
md5Holder.set(MessageDigest.getInstance("MD5"));
}
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("++++ no md5 algorythm found");
}
MessageDigest md5 = md5Holder.get();
public long hash(byte[] key) {
try {
if (md5Holder.get() == null) {
md5Holder.set(MessageDigest.getInstance("MD5"));
}
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("++++ no md5 algorythm found");
}
MessageDigest md5 = md5Holder.get();
md5.reset();
md5.update(key);
byte[] bKey = md5.digest();
long res = ((long) (bKey[3] & 0xFF) << 24)
| ((long) (bKey[2] & 0xFF) << 16)
| ((long) (bKey[1] & 0xFF) << 8) | (long) (bKey[0] & 0xFF);
return res;
}
md5.reset();
md5.update(key);
byte[] bKey = md5.digest();
long res = ((long) (bKey[3] & 0xFF) << 24)
| ((long) (bKey[2] & 0xFF) << 16)
| ((long) (bKey[1] & 0xFF) << 8) | (long) (bKey[0] & 0xFF);
return res;
}
};
public long hash(String key);

View File

@@ -10,127 +10,127 @@ import java.util.Map;
import java.util.Set;
public class JedisByteHashMap implements Map<byte[], byte[]>, Cloneable,
Serializable {
Serializable {
private static final long serialVersionUID = -6971431362627219416L;
private Map<ByteArrayWrapper, byte[]> internalMap = new HashMap<ByteArrayWrapper, byte[]>();
public void clear() {
internalMap.clear();
internalMap.clear();
}
public boolean containsKey(Object key) {
if (key instanceof byte[])
return internalMap.containsKey(new ByteArrayWrapper((byte[]) key));
return internalMap.containsKey(key);
if (key instanceof byte[])
return internalMap.containsKey(new ByteArrayWrapper((byte[]) key));
return internalMap.containsKey(key);
}
public boolean containsValue(Object value) {
return internalMap.containsValue(value);
return internalMap.containsValue(value);
}
public Set<java.util.Map.Entry<byte[], byte[]>> entrySet() {
Iterator<java.util.Map.Entry<ByteArrayWrapper, byte[]>> iterator = internalMap
.entrySet().iterator();
HashSet<Entry<byte[], byte[]>> hashSet = new HashSet<java.util.Map.Entry<byte[], byte[]>>();
while (iterator.hasNext()) {
Entry<ByteArrayWrapper, byte[]> entry = iterator.next();
hashSet.add(new JedisByteEntry(entry.getKey().data, entry
.getValue()));
}
return hashSet;
Iterator<java.util.Map.Entry<ByteArrayWrapper, byte[]>> iterator = internalMap
.entrySet().iterator();
HashSet<Entry<byte[], byte[]>> hashSet = new HashSet<java.util.Map.Entry<byte[], byte[]>>();
while (iterator.hasNext()) {
Entry<ByteArrayWrapper, byte[]> entry = iterator.next();
hashSet.add(new JedisByteEntry(entry.getKey().data, entry
.getValue()));
}
return hashSet;
}
public byte[] get(Object key) {
if (key instanceof byte[])
return internalMap.get(new ByteArrayWrapper((byte[]) key));
return internalMap.get(key);
if (key instanceof byte[])
return internalMap.get(new ByteArrayWrapper((byte[]) key));
return internalMap.get(key);
}
public boolean isEmpty() {
return internalMap.isEmpty();
return internalMap.isEmpty();
}
public Set<byte[]> keySet() {
Set<byte[]> keySet = new HashSet<byte[]>();
Iterator<ByteArrayWrapper> iterator = internalMap.keySet().iterator();
while (iterator.hasNext()) {
keySet.add(iterator.next().data);
}
return keySet;
Set<byte[]> keySet = new HashSet<byte[]>();
Iterator<ByteArrayWrapper> iterator = internalMap.keySet().iterator();
while (iterator.hasNext()) {
keySet.add(iterator.next().data);
}
return keySet;
}
public byte[] put(byte[] key, byte[] value) {
return internalMap.put(new ByteArrayWrapper(key), value);
return internalMap.put(new ByteArrayWrapper(key), value);
}
@SuppressWarnings("unchecked")
public void putAll(Map<? extends byte[], ? extends byte[]> m) {
Iterator<?> iterator = m.entrySet().iterator();
while (iterator.hasNext()) {
Entry<? extends byte[], ? extends byte[]> next = (Entry<? extends byte[], ? extends byte[]>) iterator
.next();
internalMap.put(new ByteArrayWrapper(next.getKey()),
next.getValue());
}
Iterator<?> iterator = m.entrySet().iterator();
while (iterator.hasNext()) {
Entry<? extends byte[], ? extends byte[]> next = (Entry<? extends byte[], ? extends byte[]>) iterator
.next();
internalMap.put(new ByteArrayWrapper(next.getKey()),
next.getValue());
}
}
public byte[] remove(Object key) {
if (key instanceof byte[])
return internalMap.remove(new ByteArrayWrapper((byte[]) key));
return internalMap.remove(key);
if (key instanceof byte[])
return internalMap.remove(new ByteArrayWrapper((byte[]) key));
return internalMap.remove(key);
}
public int size() {
return internalMap.size();
return internalMap.size();
}
public Collection<byte[]> values() {
return internalMap.values();
return internalMap.values();
}
private static final class ByteArrayWrapper {
private final byte[] data;
private final byte[] data;
public ByteArrayWrapper(byte[] data) {
if (data == null) {
throw new NullPointerException();
}
this.data = data;
}
public ByteArrayWrapper(byte[] data) {
if (data == null) {
throw new NullPointerException();
}
this.data = data;
}
public boolean equals(Object other) {
if (!(other instanceof ByteArrayWrapper)) {
return false;
}
return Arrays.equals(data, ((ByteArrayWrapper) other).data);
}
public boolean equals(Object other) {
if (!(other instanceof ByteArrayWrapper)) {
return false;
}
return Arrays.equals(data, ((ByteArrayWrapper) other).data);
}
public int hashCode() {
return Arrays.hashCode(data);
}
public int hashCode() {
return Arrays.hashCode(data);
}
}
private static final class JedisByteEntry implements Entry<byte[], byte[]> {
private byte[] value;
private byte[] key;
private byte[] value;
private byte[] key;
public JedisByteEntry(byte[] key, byte[] value) {
this.key = key;
this.value = value;
}
public JedisByteEntry(byte[] key, byte[] value) {
this.key = key;
this.value = value;
}
public byte[] getKey() {
return this.key;
}
public byte[] getKey() {
return this.key;
}
public byte[] getValue() {
return this.value;
}
public byte[] getValue() {
return this.value;
}
public byte[] setValue(byte[] value) {
this.value = value;
return value;
}
public byte[] setValue(byte[] value) {
this.value = value;
return value;
}
}
}

View File

@@ -9,50 +9,50 @@ package redis.clients.util;
*/
public class JedisClusterCRC16 {
private static final int LOOKUP_TABLE[] = { 0x0000, 0x1021, 0x2042, 0x3063,
0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B,
0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252,
0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A,
0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401,
0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509,
0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630,
0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738,
0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7,
0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF,
0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96,
0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E,
0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5,
0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD,
0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4,
0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC,
0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB,
0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3,
0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA,
0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2,
0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589,
0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481,
0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8,
0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0,
0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F,
0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827,
0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E,
0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16,
0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D,
0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45,
0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C,
0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74,
0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, };
0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B,
0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252,
0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A,
0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401,
0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509,
0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630,
0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738,
0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7,
0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF,
0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96,
0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E,
0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5,
0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD,
0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4,
0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC,
0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB,
0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3,
0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA,
0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2,
0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589,
0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481,
0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8,
0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0,
0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F,
0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827,
0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E,
0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16,
0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D,
0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45,
0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C,
0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74,
0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, };
public static int getSlot(String key) {
int s = key.indexOf("{");
if (s > -1) {
int e = key.indexOf("}", s + 1);
if (e > -1 && e != s + 1) {
key = key.substring(s + 1, e);
}
}
// optimization with modulo operator with power of 2
// equivalent to getCRC16(key) % 16384
return getCRC16(key) & (16384 - 1);
int s = key.indexOf("{");
if (s > -1) {
int e = key.indexOf("}", s + 1);
if (e > -1 && e != s + 1) {
key = key.substring(s + 1, e);
}
}
// optimization with modulo operator with power of 2
// equivalent to getCRC16(key) % 16384
return getCRC16(key) & (16384 - 1);
}
/**
@@ -64,16 +64,16 @@ public class JedisClusterCRC16 {
* @see https://github.com/xetorthio/jedis/pull/733#issuecomment-55840331
*/
public static int getCRC16(byte[] bytes) {
int crc = 0x0000;
int crc = 0x0000;
for (byte b : bytes) {
crc = ((crc << 8) ^ LOOKUP_TABLE[((crc >>> 8) ^ (b & 0xFF)) & 0xFF]);
}
return crc & 0xFFFF;
for (byte b : bytes) {
crc = ((crc << 8) ^ LOOKUP_TABLE[((crc >>> 8) ^ (b & 0xFF)) & 0xFF]);
}
return crc & 0xFFFF;
}
public static int getCRC16(String key) {
return getCRC16(SafeEncoder.encode(key));
return getCRC16(SafeEncoder.encode(key));
}
}

View File

@@ -4,23 +4,23 @@ import java.net.URI;
public class JedisURIHelper {
public static String getPassword(URI uri) {
String userInfo = uri.getUserInfo();
if (userInfo != null) {
return userInfo.split(":", 2)[1];
}
return null;
String userInfo = uri.getUserInfo();
if (userInfo != null) {
return userInfo.split(":", 2)[1];
}
return null;
}
public static Integer getDBIndex(URI uri) {
String[] pathSplit = uri.getPath().split("/", 2);
if (pathSplit.length > 1) {
String dbIndexStr = pathSplit[1];
if (dbIndexStr.isEmpty()) {
return 0;
}
return Integer.parseInt(dbIndexStr);
} else {
return 0;
}
String[] pathSplit = uri.getPath().split("/", 2);
if (pathSplit.length > 1) {
String dbIndexStr = pathSplit[1];
if (dbIndexStr.isEmpty()) {
return 0;
}
return Integer.parseInt(dbIndexStr);
} else {
return 0;
}
}
}

View File

@@ -40,7 +40,7 @@ public class MurmurHash implements Hashing {
* @return The 32 bit hash of the bytes in question.
*/
public static int hash(byte[] data, int seed) {
return hash(ByteBuffer.wrap(data), seed);
return hash(ByteBuffer.wrap(data), seed);
}
/**
@@ -57,7 +57,7 @@ public class MurmurHash implements Hashing {
* @return The 32-bit hash of the data in question.
*/
public static int hash(byte[] data, int offset, int length, int seed) {
return hash(ByteBuffer.wrap(data, offset, length), seed);
return hash(ByteBuffer.wrap(data, offset, length), seed);
}
/**
@@ -70,97 +70,97 @@ public class MurmurHash implements Hashing {
* @return The 32 bit murmur hash of the bytes in the buffer.
*/
public static int hash(ByteBuffer buf, int seed) {
// save byte order for later restoration
ByteOrder byteOrder = buf.order();
buf.order(ByteOrder.LITTLE_ENDIAN);
// save byte order for later restoration
ByteOrder byteOrder = buf.order();
buf.order(ByteOrder.LITTLE_ENDIAN);
int m = 0x5bd1e995;
int r = 24;
int m = 0x5bd1e995;
int r = 24;
int h = seed ^ buf.remaining();
int h = seed ^ buf.remaining();
int k;
while (buf.remaining() >= 4) {
k = buf.getInt();
int k;
while (buf.remaining() >= 4) {
k = buf.getInt();
k *= m;
k ^= k >>> r;
k *= m;
k *= m;
k ^= k >>> r;
k *= m;
h *= m;
h ^= k;
}
h *= m;
h ^= k;
}
if (buf.remaining() > 0) {
ByteBuffer finish = ByteBuffer.allocate(4).order(
ByteOrder.LITTLE_ENDIAN);
// for big-endian version, use this first:
// finish.position(4-buf.remaining());
finish.put(buf).rewind();
h ^= finish.getInt();
h *= m;
}
if (buf.remaining() > 0) {
ByteBuffer finish = ByteBuffer.allocate(4).order(
ByteOrder.LITTLE_ENDIAN);
// for big-endian version, use this first:
// finish.position(4-buf.remaining());
finish.put(buf).rewind();
h ^= finish.getInt();
h *= m;
}
h ^= h >>> 13;
h *= m;
h ^= h >>> 15;
h ^= h >>> 13;
h *= m;
h ^= h >>> 15;
buf.order(byteOrder);
return h;
buf.order(byteOrder);
return h;
}
public static long hash64A(byte[] data, int seed) {
return hash64A(ByteBuffer.wrap(data), seed);
return hash64A(ByteBuffer.wrap(data), seed);
}
public static long hash64A(byte[] data, int offset, int length, int seed) {
return hash64A(ByteBuffer.wrap(data, offset, length), seed);
return hash64A(ByteBuffer.wrap(data, offset, length), seed);
}
public static long hash64A(ByteBuffer buf, int seed) {
ByteOrder byteOrder = buf.order();
buf.order(ByteOrder.LITTLE_ENDIAN);
ByteOrder byteOrder = buf.order();
buf.order(ByteOrder.LITTLE_ENDIAN);
long m = 0xc6a4a7935bd1e995L;
int r = 47;
long m = 0xc6a4a7935bd1e995L;
int r = 47;
long h = seed ^ (buf.remaining() * m);
long h = seed ^ (buf.remaining() * m);
long k;
while (buf.remaining() >= 8) {
k = buf.getLong();
long k;
while (buf.remaining() >= 8) {
k = buf.getLong();
k *= m;
k ^= k >>> r;
k *= m;
k *= m;
k ^= k >>> r;
k *= m;
h ^= k;
h *= m;
}
h ^= k;
h *= m;
}
if (buf.remaining() > 0) {
ByteBuffer finish = ByteBuffer.allocate(8).order(
ByteOrder.LITTLE_ENDIAN);
// for big-endian version, do this first:
// finish.position(8-buf.remaining());
finish.put(buf).rewind();
h ^= finish.getLong();
h *= m;
}
if (buf.remaining() > 0) {
ByteBuffer finish = ByteBuffer.allocate(8).order(
ByteOrder.LITTLE_ENDIAN);
// for big-endian version, do this first:
// finish.position(8-buf.remaining());
finish.put(buf).rewind();
h ^= finish.getLong();
h *= m;
}
h ^= h >>> r;
h *= m;
h ^= h >>> r;
h ^= h >>> r;
h *= m;
h ^= h >>> r;
buf.order(byteOrder);
return h;
buf.order(byteOrder);
return h;
}
public long hash(byte[] key) {
return hash64A(key, 0x1234ABCD);
return hash64A(key, 0x1234ABCD);
}
public long hash(String key) {
return hash(SafeEncoder.encode(key));
return hash(SafeEncoder.encode(key));
}
}

View File

@@ -21,82 +21,82 @@ public abstract class Pool<T> implements Closeable {
@Override
public void close() {
closeInternalPool();
closeInternalPool();
}
public boolean isClosed() {
return this.internalPool.isClosed();
return this.internalPool.isClosed();
}
public Pool(final GenericObjectPoolConfig poolConfig,
PooledObjectFactory<T> factory) {
initPool(poolConfig, factory);
PooledObjectFactory<T> factory) {
initPool(poolConfig, factory);
}
public void initPool(final GenericObjectPoolConfig poolConfig,
PooledObjectFactory<T> factory) {
PooledObjectFactory<T> factory) {
if (this.internalPool != null) {
try {
closeInternalPool();
} catch (Exception e) {
}
}
if (this.internalPool != null) {
try {
closeInternalPool();
} catch (Exception e) {
}
}
this.internalPool = new GenericObjectPool<T>(factory, poolConfig);
this.internalPool = new GenericObjectPool<T>(factory, poolConfig);
}
public T getResource() {
try {
return internalPool.borrowObject();
} catch (Exception e) {
throw new JedisConnectionException(
"Could not get a resource from the pool", e);
}
try {
return internalPool.borrowObject();
} catch (Exception e) {
throw new JedisConnectionException(
"Could not get a resource from the pool", e);
}
}
public void returnResourceObject(final T resource) {
if (resource == null) {
return;
}
try {
internalPool.returnObject(resource);
} catch (Exception e) {
throw new JedisException(
"Could not return the resource to the pool", e);
}
if (resource == null) {
return;
}
try {
internalPool.returnObject(resource);
} catch (Exception e) {
throw new JedisException(
"Could not return the resource to the pool", e);
}
}
public void returnBrokenResource(final T resource) {
if (resource != null) {
returnBrokenResourceObject(resource);
}
if (resource != null) {
returnBrokenResourceObject(resource);
}
}
public void returnResource(final T resource) {
if (resource != null) {
returnResourceObject(resource);
}
if (resource != null) {
returnResourceObject(resource);
}
}
public void destroy() {
closeInternalPool();
closeInternalPool();
}
protected void returnBrokenResourceObject(final T resource) {
try {
internalPool.invalidateObject(resource);
} catch (Exception e) {
throw new JedisException(
"Could not return the resource to the pool", e);
}
try {
internalPool.invalidateObject(resource);
} catch (Exception e) {
throw new JedisException(
"Could not return the resource to the pool", e);
}
}
protected void closeInternalPool() {
try {
internalPool.close();
} catch (Exception e) {
throw new JedisException("Could not destroy the pool", e);
}
try {
internalPool.close();
} catch (Exception e) {
throw new JedisException("Could not destroy the pool", e);
}
}
}

View File

@@ -16,12 +16,15 @@
package redis.clients.util;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;
import redis.clients.jedis.exceptions.JedisConnectionException;
/**
* This class assumes (to some degree) that we are reading a RESP stream. As such it assumes
* certain conventions regarding CRLF line termination. It also assumes that if the Protocol
* layer requires a byte that if that byte is not there it is a stream error.
*/
public class RedisInputStream extends FilterInputStream {
protected final byte buf[];
@@ -29,84 +32,183 @@ public class RedisInputStream extends FilterInputStream {
protected int count, limit;
public RedisInputStream(InputStream in, int size) {
super(in);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
super(in);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
public RedisInputStream(InputStream in) {
this(in, 8192);
this(in, 8192);
}
public byte readByte() throws IOException {
if (count == limit) {
fill();
}
return buf[count++];
public byte readByte() throws JedisConnectionException {
ensureFill();
return buf[count++];
}
public String readLine() {
int b;
byte c;
StringBuilder sb = new StringBuilder();
final StringBuilder sb = new StringBuilder();
while (true) {
ensureFill();
try {
while (true) {
if (count == limit) {
fill();
}
if (limit == -1)
break;
byte b = buf[count++];
if (b == '\r') {
ensureFill(); // Must be one more byte
b = buf[count++];
if (b == '\r') {
if (count == limit) {
fill();
}
if (limit == -1) {
sb.append((char) b);
break;
}
c = buf[count++];
if (c == '\n') {
break;
}
sb.append((char) b);
sb.append((char) c);
} else {
sb.append((char) b);
}
}
} catch (IOException e) {
throw new JedisConnectionException(e);
}
String reply = sb.toString();
if (reply.length() == 0) {
throw new JedisConnectionException(
"It seems like server has closed the connection.");
}
return reply;
byte c = buf[count++];
if (c == '\n') {
break;
}
sb.append((char) b);
sb.append((char) c);
} else {
sb.append((char) b);
}
}
public int read(byte[] b, int off, int len) throws IOException {
if (count == limit) {
fill();
if (limit == -1)
return -1;
}
final int length = Math.min(limit - count, len);
System.arraycopy(buf, count, b, off, length);
count += length;
return length;
final String reply = sb.toString();
if (reply.length() == 0) {
throw new JedisConnectionException("It seems like server has closed the connection.");
}
private void fill() throws IOException {
limit = in.read(buf);
count = 0;
return reply;
}
public byte[] readLineBytes() {
/* This operation should only require one fill. In that typical
case we optimize allocation and copy of the byte array. In the
edge case where more than one fill is required then we take a
slower path and expand a byte array output stream as is
necessary. */
ensureFill();
int pos = count;
final byte[] buf = this.buf;
while (true) {
if (pos == limit) {
return readLineBytesSlowly();
}
if (buf[pos++] == '\r') {
if (pos == limit) {
return readLineBytesSlowly();
}
if (buf[pos++] == '\n') {
break;
}
}
}
final int N = (pos - count) - 2;
final byte[] line = new byte[N];
System.arraycopy(buf, count, line, 0, N);
count = pos;
return line;
}
/**
* Slow path in case a line of bytes cannot be read in one #fill() operation. This is still faster
* than creating the StrinbBuilder, String, then encoding as byte[] in Protocol, then decoding back
* into a String.
*/
private byte[] readLineBytesSlowly() {
ByteArrayOutputStream bout = null;
while (true) {
ensureFill();
byte b = buf[count++];
if (b == '\r') {
ensureFill(); // Must be one more byte
byte c = buf[count++];
if (c == '\n') {
break;
}
if (bout == null) {
bout = new ByteArrayOutputStream(16);
}
bout.write(b);
bout.write(c);
} else {
if (bout == null) {
bout = new ByteArrayOutputStream(16);
}
bout.write(b);
}
}
return bout == null ? new byte[0] : bout.toByteArray();
}
public int readIntCrLf() {
return (int)readLongCrLf();
}
public long readLongCrLf() {
final byte[] buf = this.buf;
ensureFill();
final boolean isNeg = buf[count] == '-';
if (isNeg) {
++count;
}
long value = 0;
while (true) {
ensureFill();
final int b = buf[count++];
if (b == '\r') {
ensureFill();
if (buf[count++] != '\n') {
throw new JedisConnectionException("Unexpected character!");
}
break;
}
else {
value = value * 10 + b - '0';
}
}
return (isNeg ? -value : value);
}
public int read(byte[] b, int off, int len) throws JedisConnectionException {
ensureFill();
final int length = Math.min(limit - count, len);
System.arraycopy(buf, count, b, off, length);
count += length;
return length;
}
/**
* This methods assumes there are required bytes to be read. If we cannot read
* anymore bytes an exception is thrown to quickly ascertain that the stream
* was smaller than expected.
*/
private void ensureFill() throws JedisConnectionException {
if (count >= limit) {
try {
limit = in.read(buf);
count = 0;
if (limit == -1) {
throw new JedisConnectionException("Unexpected end of stream.");
}
} catch (IOException e) {
throw new JedisConnectionException(e);
}
}
}
}

View File

@@ -15,212 +15,212 @@ public final class RedisOutputStream extends FilterOutputStream {
protected int count;
public RedisOutputStream(final OutputStream out) {
this(out, 8192);
this(out, 8192);
}
public RedisOutputStream(final OutputStream out, final int size) {
super(out);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
super(out);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
private void flushBuffer() throws IOException {
if (count > 0) {
out.write(buf, 0, count);
count = 0;
}
if (count > 0) {
out.write(buf, 0, count);
count = 0;
}
}
public void write(final byte b) throws IOException {
if (count == buf.length) {
flushBuffer();
}
buf[count++] = b;
if (count == buf.length) {
flushBuffer();
}
buf[count++] = b;
}
public void write(final byte[] b) throws IOException {
write(b, 0, b.length);
write(b, 0, b.length);
}
public void write(final byte b[], final int off, final int len)
throws IOException {
if (len >= buf.length) {
flushBuffer();
out.write(b, off, len);
} else {
if (len >= buf.length - count) {
flushBuffer();
}
throws IOException {
if (len >= buf.length) {
flushBuffer();
out.write(b, off, len);
} else {
if (len >= buf.length - count) {
flushBuffer();
}
System.arraycopy(b, off, buf, count, len);
count += len;
}
System.arraycopy(b, off, buf, count, len);
count += len;
}
}
public void writeAsciiCrLf(final String in) throws IOException {
final int size = in.length();
final int size = in.length();
for (int i = 0; i != size; ++i) {
if (count == buf.length) {
flushBuffer();
}
buf[count++] = (byte) in.charAt(i);
}
for (int i = 0; i != size; ++i) {
if (count == buf.length) {
flushBuffer();
}
buf[count++] = (byte) in.charAt(i);
}
writeCrLf();
writeCrLf();
}
public static boolean isSurrogate(final char ch) {
return ch >= Character.MIN_SURROGATE && ch <= Character.MAX_SURROGATE;
return ch >= Character.MIN_SURROGATE && ch <= Character.MAX_SURROGATE;
}
public static int utf8Length(final String str) {
int strLen = str.length(), utfLen = 0;
for (int i = 0; i != strLen; ++i) {
char c = str.charAt(i);
if (c < 0x80) {
utfLen++;
} else if (c < 0x800) {
utfLen += 2;
} else if (isSurrogate(c)) {
i++;
utfLen += 4;
} else {
utfLen += 3;
}
}
return utfLen;
int strLen = str.length(), utfLen = 0;
for (int i = 0; i != strLen; ++i) {
char c = str.charAt(i);
if (c < 0x80) {
utfLen++;
} else if (c < 0x800) {
utfLen += 2;
} else if (isSurrogate(c)) {
i++;
utfLen += 4;
} else {
utfLen += 3;
}
}
return utfLen;
}
public void writeCrLf() throws IOException {
if (2 >= buf.length - count) {
flushBuffer();
}
if (2 >= buf.length - count) {
flushBuffer();
}
buf[count++] = '\r';
buf[count++] = '\n';
buf[count++] = '\r';
buf[count++] = '\n';
}
public void writeUtf8CrLf(final String str) throws IOException {
int strLen = str.length();
int strLen = str.length();
int i;
for (i = 0; i < strLen; i++) {
char c = str.charAt(i);
if (!(c < 0x80))
break;
if (count == buf.length) {
flushBuffer();
}
buf[count++] = (byte) c;
}
int i;
for (i = 0; i < strLen; i++) {
char c = str.charAt(i);
if (!(c < 0x80))
break;
if (count == buf.length) {
flushBuffer();
}
buf[count++] = (byte) c;
}
for (; i < strLen; i++) {
char c = str.charAt(i);
if (c < 0x80) {
if (count == buf.length) {
flushBuffer();
}
buf[count++] = (byte) c;
} else if (c < 0x800) {
if (2 >= buf.length - count) {
flushBuffer();
}
buf[count++] = (byte) (0xc0 | (c >> 6));
buf[count++] = (byte) (0x80 | (c & 0x3f));
} else if (isSurrogate(c)) {
if (4 >= buf.length - count) {
flushBuffer();
}
int uc = Character.toCodePoint(c, str.charAt(i++));
buf[count++] = ((byte) (0xf0 | ((uc >> 18))));
buf[count++] = ((byte) (0x80 | ((uc >> 12) & 0x3f)));
buf[count++] = ((byte) (0x80 | ((uc >> 6) & 0x3f)));
buf[count++] = ((byte) (0x80 | (uc & 0x3f)));
} else {
if (3 >= buf.length - count) {
flushBuffer();
}
buf[count++] = ((byte) (0xe0 | ((c >> 12))));
buf[count++] = ((byte) (0x80 | ((c >> 6) & 0x3f)));
buf[count++] = ((byte) (0x80 | (c & 0x3f)));
}
}
for (; i < strLen; i++) {
char c = str.charAt(i);
if (c < 0x80) {
if (count == buf.length) {
flushBuffer();
}
buf[count++] = (byte) c;
} else if (c < 0x800) {
if (2 >= buf.length - count) {
flushBuffer();
}
buf[count++] = (byte) (0xc0 | (c >> 6));
buf[count++] = (byte) (0x80 | (c & 0x3f));
} else if (isSurrogate(c)) {
if (4 >= buf.length - count) {
flushBuffer();
}
int uc = Character.toCodePoint(c, str.charAt(i++));
buf[count++] = ((byte) (0xf0 | ((uc >> 18))));
buf[count++] = ((byte) (0x80 | ((uc >> 12) & 0x3f)));
buf[count++] = ((byte) (0x80 | ((uc >> 6) & 0x3f)));
buf[count++] = ((byte) (0x80 | (uc & 0x3f)));
} else {
if (3 >= buf.length - count) {
flushBuffer();
}
buf[count++] = ((byte) (0xe0 | ((c >> 12))));
buf[count++] = ((byte) (0x80 | ((c >> 6) & 0x3f)));
buf[count++] = ((byte) (0x80 | (c & 0x3f)));
}
}
writeCrLf();
writeCrLf();
}
private final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999,
9999999, 99999999, 999999999, Integer.MAX_VALUE };
9999999, 99999999, 999999999, Integer.MAX_VALUE };
private final static byte[] DigitTens = { '0', '0', '0', '0', '0', '0',
'0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3',
'3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4',
'4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5',
'5', '5', '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '7',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', '8',
'8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9',
'9', '9', '9', };
'0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3',
'3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4',
'4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5',
'5', '5', '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '7',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', '8',
'8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9',
'9', '9', '9', };
private final static byte[] DigitOnes = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1',
'2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', };
'6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1',
'2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', };
private final static byte[] digits = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z' };
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z' };
public void writeIntCrLf(int value) throws IOException {
if (value < 0) {
write((byte) '-');
value = -value;
}
if (value < 0) {
write((byte) '-');
value = -value;
}
int size = 0;
while (value > sizeTable[size])
size++;
int size = 0;
while (value > sizeTable[size])
size++;
size++;
if (size >= buf.length - count) {
flushBuffer();
}
size++;
if (size >= buf.length - count) {
flushBuffer();
}
int q, r;
int charPos = count + size;
int q, r;
int charPos = count + size;
while (value >= 65536) {
q = value / 100;
r = value - ((q << 6) + (q << 5) + (q << 2));
value = q;
buf[--charPos] = DigitOnes[r];
buf[--charPos] = DigitTens[r];
}
while (value >= 65536) {
q = value / 100;
r = value - ((q << 6) + (q << 5) + (q << 2));
value = q;
buf[--charPos] = DigitOnes[r];
buf[--charPos] = DigitTens[r];
}
for (;;) {
q = (value * 52429) >>> (16 + 3);
r = value - ((q << 3) + (q << 1));
buf[--charPos] = digits[r];
value = q;
if (value == 0)
break;
}
count += size;
for (;;) {
q = (value * 52429) >>> (16 + 3);
r = value - ((q << 3) + (q << 1));
buf[--charPos] = digits[r];
value = q;
if (value == 0)
break;
}
count += size;
writeCrLf();
writeCrLf();
}
public void flush() throws IOException {
flushBuffer();
out.flush();
flushBuffer();
out.flush();
}
}

View File

@@ -12,30 +12,30 @@ import redis.clients.jedis.exceptions.JedisException;
*/
public class SafeEncoder {
public static byte[][] encodeMany(final String... strs) {
byte[][] many = new byte[strs.length][];
for (int i = 0; i < strs.length; i++) {
many[i] = encode(strs[i]);
}
return many;
byte[][] many = new byte[strs.length][];
for (int i = 0; i < strs.length; i++) {
many[i] = encode(strs[i]);
}
return many;
}
public static byte[] encode(final String str) {
try {
if (str == null) {
throw new JedisDataException(
"value sent to redis cannot be null");
}
return str.getBytes(Protocol.CHARSET);
} catch (UnsupportedEncodingException e) {
throw new JedisException(e);
}
try {
if (str == null) {
throw new JedisDataException(
"value sent to redis cannot be null");
}
return str.getBytes(Protocol.CHARSET);
} catch (UnsupportedEncodingException e) {
throw new JedisException(e);
}
}
public static String encode(final byte[] data) {
try {
return new String(data, Protocol.CHARSET);
} catch (UnsupportedEncodingException e) {
throw new JedisException(e);
}
try {
return new String(data, Protocol.CHARSET);
} catch (UnsupportedEncodingException e) {
throw new JedisException(e);
}
}
}

View File

@@ -7,11 +7,11 @@ public abstract class ShardInfo<T> {
}
public ShardInfo(int weight) {
this.weight = weight;
this.weight = weight;
}
public int getWeight() {
return this.weight;
return this.weight;
}
protected abstract T createResource();

View File

@@ -26,68 +26,68 @@ public class Sharded<R, S extends ShardInfo<R>> {
private Pattern tagPattern = null;
// the tag is anything between {}
public static final Pattern DEFAULT_KEY_TAG_PATTERN = Pattern
.compile("\\{(.+?)\\}");
.compile("\\{(.+?)\\}");
public Sharded(List<S> shards) {
this(shards, Hashing.MURMUR_HASH); // MD5 is really not good as we works
// with 64-bits not 128
this(shards, Hashing.MURMUR_HASH); // MD5 is really not good as we works
// with 64-bits not 128
}
public Sharded(List<S> shards, Hashing algo) {
this.algo = algo;
initialize(shards);
this.algo = algo;
initialize(shards);
}
public Sharded(List<S> shards, Pattern tagPattern) {
this(shards, Hashing.MURMUR_HASH, tagPattern); // MD5 is really not good
// as we works with
// 64-bits not 128
this(shards, Hashing.MURMUR_HASH, tagPattern); // MD5 is really not good
// as we works with
// 64-bits not 128
}
public Sharded(List<S> shards, Hashing algo, Pattern tagPattern) {
this.algo = algo;
this.tagPattern = tagPattern;
initialize(shards);
this.algo = algo;
this.tagPattern = tagPattern;
initialize(shards);
}
private void initialize(List<S> shards) {
nodes = new TreeMap<Long, S>();
nodes = new TreeMap<Long, S>();
for (int i = 0; i != shards.size(); ++i) {
final S shardInfo = shards.get(i);
if (shardInfo.getName() == null)
for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {
nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n),
shardInfo);
}
else
for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {
nodes.put(
this.algo.hash(shardInfo.getName() + "*"
+ shardInfo.getWeight() + n), shardInfo);
}
resources.put(shardInfo, shardInfo.createResource());
}
for (int i = 0; i != shards.size(); ++i) {
final S shardInfo = shards.get(i);
if (shardInfo.getName() == null)
for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {
nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n),
shardInfo);
}
else
for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {
nodes.put(
this.algo.hash(shardInfo.getName() + "*"
+ shardInfo.getWeight() + n), shardInfo);
}
resources.put(shardInfo, shardInfo.createResource());
}
}
public R getShard(byte[] key) {
return resources.get(getShardInfo(key));
return resources.get(getShardInfo(key));
}
public R getShard(String key) {
return resources.get(getShardInfo(key));
return resources.get(getShardInfo(key));
}
public S getShardInfo(byte[] key) {
SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key));
if (tail.isEmpty()) {
return nodes.get(nodes.firstKey());
}
return tail.get(tail.firstKey());
SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key));
if (tail.isEmpty()) {
return nodes.get(nodes.firstKey());
}
return tail.get(tail.firstKey());
}
public S getShardInfo(String key) {
return getShardInfo(SafeEncoder.encode(getKeyTag(key)));
return getShardInfo(SafeEncoder.encode(getKeyTag(key)));
}
/**
@@ -100,19 +100,19 @@ public class Sharded<R, S extends ShardInfo<R>> {
* @return The tag if it exists, or the original key
*/
public String getKeyTag(String key) {
if (tagPattern != null) {
Matcher m = tagPattern.matcher(key);
if (m.find())
return m.group(1);
}
return key;
if (tagPattern != null) {
Matcher m = tagPattern.matcher(key);
if (m.find())
return m.group(1);
}
return key;
}
public Collection<S> getAllShardInfo() {
return Collections.unmodifiableCollection(nodes.values());
return Collections.unmodifiableCollection(nodes.values());
}
public Collection<R> getAllShards() {
return Collections.unmodifiableCollection(resources.values());
return Collections.unmodifiableCollection(resources.values());
}
}

View File

@@ -11,43 +11,43 @@ public class Slowlog {
@SuppressWarnings("unchecked")
public static List<Slowlog> from(List<Object> nestedMultiBulkReply) {
List<Slowlog> logs = new ArrayList<Slowlog>(nestedMultiBulkReply.size());
for (Object obj : nestedMultiBulkReply) {
List<Object> properties = (List<Object>) obj;
logs.add(new Slowlog(properties));
}
List<Slowlog> logs = new ArrayList<Slowlog>(nestedMultiBulkReply.size());
for (Object obj : nestedMultiBulkReply) {
List<Object> properties = (List<Object>) obj;
logs.add(new Slowlog(properties));
}
return logs;
return logs;
}
@SuppressWarnings("unchecked")
private Slowlog(List<Object> properties) {
super();
this.id = (Long) properties.get(0);
this.timeStamp = (Long) properties.get(1);
this.executionTime = (Long) properties.get(2);
super();
this.id = (Long) properties.get(0);
this.timeStamp = (Long) properties.get(1);
this.executionTime = (Long) properties.get(2);
List<byte[]> bargs = (List<byte[]>) properties.get(3);
this.args = new ArrayList<String>(bargs.size());
List<byte[]> bargs = (List<byte[]>) properties.get(3);
this.args = new ArrayList<String>(bargs.size());
for (byte[] barg : bargs) {
this.args.add(SafeEncoder.encode(barg));
}
for (byte[] barg : bargs) {
this.args.add(SafeEncoder.encode(barg));
}
}
public long getId() {
return id;
return id;
}
public long getTimeStamp() {
return timeStamp;
return timeStamp;
}
public long getExecutionTime() {
return executionTime;
return executionTime;
}
public List<String> getArgs() {
return args;
return args;
}
}

View File

@@ -8,7 +8,7 @@ import redis.clients.jedis.BuilderFactory;
public class BuilderFactoryTest extends Assert {
@Test
public void buildDouble() {
Double build = BuilderFactory.DOUBLE.build("1.0".getBytes());
assertEquals(new Double(1.0), build);
Double build = BuilderFactory.DOUBLE.build("1.0".getBytes());
assertEquals(new Double(1.0), build);
}
}

View File

@@ -14,31 +14,31 @@ public class ConnectionCloseTest extends Assert {
@Before
public void setUp() throws Exception {
client = new Connection();
client = new Connection();
}
@After
public void tearDown() throws Exception {
client.close();
client.close();
}
@Test(expected = JedisConnectionException.class)
public void checkUnkownHost() {
client.setHost("someunknownhost");
client.connect();
client.setHost("someunknownhost");
client.connect();
}
@Test(expected = JedisConnectionException.class)
public void checkWrongPort() {
client.setHost("localhost");
client.setPort(55665);
client.connect();
client.setHost("localhost");
client.setPort(55665);
client.connect();
}
@Test
public void connectIfNotConnectedWhenSettingTimeoutInfinite() {
client.setHost("localhost");
client.setPort(6379);
client.setTimeoutInfinite();
client.setHost("localhost");
client.setPort(6379);
client.setTimeoutInfinite();
}
}

View File

@@ -13,39 +13,39 @@ public class ConnectionTest extends Assert {
@Before
public void setUp() throws Exception {
client = new Connection();
client = new Connection();
}
@After
public void tearDown() throws Exception {
client.disconnect();
client.disconnect();
}
@Test(expected = JedisConnectionException.class)
public void checkUnkownHost() {
client.setHost("someunknownhost");
client.connect();
client.setHost("someunknownhost");
client.connect();
}
@Test(expected = JedisConnectionException.class)
public void checkWrongPort() {
client.setHost("localhost");
client.setPort(55665);
client.connect();
client.setHost("localhost");
client.setPort(55665);
client.connect();
}
@Test
public void connectIfNotConnectedWhenSettingTimeoutInfinite() {
client.setHost("localhost");
client.setPort(6379);
client.setTimeoutInfinite();
client.setHost("localhost");
client.setPort(6379);
client.setTimeoutInfinite();
}
@Test
public void checkCloseable() {
client.setHost("localhost");
client.setPort(6379);
client.connect();
client.close();
client.setHost("localhost");
client.setPort(6379);
client.connect();
client.close();
}
}

View File

@@ -9,22 +9,22 @@ public class FragmentedByteArrayInputStream extends ByteArrayInputStream {
private int readMethodCallCount = 0;
public FragmentedByteArrayInputStream(final byte[] buf) {
super(buf);
super(buf);
}
public synchronized int read(final byte[] b, final int off, final int len) {
readMethodCallCount++;
if (len <= 10) {
// if the len <= 10, return as usual ..
return super.read(b, off, len);
} else {
// else return the first half ..
return super.read(b, off, len / 2);
}
readMethodCallCount++;
if (len <= 10) {
// if the len <= 10, return as usual ..
return super.read(b, off, len);
} else {
// else return the first half ..
return super.read(b, off, len / 2);
}
}
public int getReadMethodCallCount() {
return readMethodCallCount;
return readMethodCallCount;
}
}

View File

@@ -12,93 +12,93 @@ public class HostAndPortUtil {
private static List<HostAndPort> clusterHostAndPortList = new ArrayList<HostAndPort>();
static {
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 1));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 2));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 3));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 4));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 5));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 6));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 1));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 2));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 3));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 4));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 5));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 6));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 1));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 2));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 3));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 1));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 2));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 3));
clusterHostAndPortList.add(new HostAndPort("localhost", 7379));
clusterHostAndPortList.add(new HostAndPort("localhost", 7380));
clusterHostAndPortList.add(new HostAndPort("localhost", 7381));
clusterHostAndPortList.add(new HostAndPort("localhost", 7382));
clusterHostAndPortList.add(new HostAndPort("localhost", 7383));
clusterHostAndPortList.add(new HostAndPort("localhost", 7384));
clusterHostAndPortList.add(new HostAndPort("localhost", 7379));
clusterHostAndPortList.add(new HostAndPort("localhost", 7380));
clusterHostAndPortList.add(new HostAndPort("localhost", 7381));
clusterHostAndPortList.add(new HostAndPort("localhost", 7382));
clusterHostAndPortList.add(new HostAndPort("localhost", 7383));
clusterHostAndPortList.add(new HostAndPort("localhost", 7384));
String envRedisHosts = System.getProperty("redis-hosts");
String envSentinelHosts = System.getProperty("sentinel-hosts");
String envClusterHosts = System.getProperty("cluster-hosts");
String envRedisHosts = System.getProperty("redis-hosts");
String envSentinelHosts = System.getProperty("sentinel-hosts");
String envClusterHosts = System.getProperty("cluster-hosts");
redisHostAndPortList = parseHosts(envRedisHosts, redisHostAndPortList);
sentinelHostAndPortList = parseHosts(envSentinelHosts,
sentinelHostAndPortList);
clusterHostAndPortList = parseHosts(envClusterHosts,
clusterHostAndPortList);
redisHostAndPortList = parseHosts(envRedisHosts, redisHostAndPortList);
sentinelHostAndPortList = parseHosts(envSentinelHosts,
sentinelHostAndPortList);
clusterHostAndPortList = parseHosts(envClusterHosts,
clusterHostAndPortList);
}
public static List<HostAndPort> parseHosts(String envHosts,
List<HostAndPort> existingHostsAndPorts) {
List<HostAndPort> existingHostsAndPorts) {
if (null != envHosts && 0 < envHosts.length()) {
if (null != envHosts && 0 < envHosts.length()) {
String[] hostDefs = envHosts.split(",");
String[] hostDefs = envHosts.split(",");
if (null != hostDefs && 2 <= hostDefs.length) {
if (null != hostDefs && 2 <= hostDefs.length) {
List<HostAndPort> envHostsAndPorts = new ArrayList<HostAndPort>(
hostDefs.length);
List<HostAndPort> envHostsAndPorts = new ArrayList<HostAndPort>(
hostDefs.length);
for (String hostDef : hostDefs) {
for (String hostDef : hostDefs) {
String[] hostAndPort = hostDef.split(":");
String[] hostAndPort = hostDef.split(":");
if (null != hostAndPort && 2 == hostAndPort.length) {
String host = hostAndPort[0];
int port = Protocol.DEFAULT_PORT;
if (null != hostAndPort && 2 == hostAndPort.length) {
String host = hostAndPort[0];
int port = Protocol.DEFAULT_PORT;
try {
port = Integer.parseInt(hostAndPort[1]);
} catch (final NumberFormatException nfe) {
}
try {
port = Integer.parseInt(hostAndPort[1]);
} catch (final NumberFormatException nfe) {
}
envHostsAndPorts.add(new HostAndPort(host, port));
}
}
envHostsAndPorts.add(new HostAndPort(host, port));
}
}
return envHostsAndPorts;
}
}
return envHostsAndPorts;
}
}
return existingHostsAndPorts;
return existingHostsAndPorts;
}
public static List<HostAndPort> getRedisServers() {
return redisHostAndPortList;
return redisHostAndPortList;
}
public static List<HostAndPort> getSentinelServers() {
return sentinelHostAndPortList;
return sentinelHostAndPortList;
}
public static List<HostAndPort> getClusterServers() {
return clusterHostAndPortList;
return clusterHostAndPortList;
}
}

View File

@@ -13,52 +13,52 @@ public class JedisClusterNodeInformationParserTest extends Assert {
@Before
public void setUp() {
parser = new ClusterNodeInformationParser();
parser = new ClusterNodeInformationParser();
}
@Test
public void testParseNodeMyself() {
String nodeInfo = "9b0d2ab38ee31482c95fdb2c7847a0d40e88d518 :7379 myself,master - 0 0 1 connected 0-5460";
HostAndPort current = new HostAndPort("localhost", 7379);
ClusterNodeInformation clusterNodeInfo = parser
.parse(nodeInfo, current);
assertEquals(clusterNodeInfo.getNode(), current);
String nodeInfo = "9b0d2ab38ee31482c95fdb2c7847a0d40e88d518 :7379 myself,master - 0 0 1 connected 0-5460";
HostAndPort current = new HostAndPort("localhost", 7379);
ClusterNodeInformation clusterNodeInfo = parser
.parse(nodeInfo, current);
assertEquals(clusterNodeInfo.getNode(), current);
}
@Test
public void testParseNormalState() {
String nodeInfo = "5f4a2236d00008fba7ac0dd24b95762b446767bd 192.168.0.3:7380 master - 0 1400598804016 2 connected 5461-10922";
HostAndPort current = new HostAndPort("localhost", 7379);
ClusterNodeInformation clusterNodeInfo = parser
.parse(nodeInfo, current);
assertNotEquals(clusterNodeInfo.getNode(), current);
assertEquals(clusterNodeInfo.getNode(), new HostAndPort("192.168.0.3",
7380));
String nodeInfo = "5f4a2236d00008fba7ac0dd24b95762b446767bd 192.168.0.3:7380 master - 0 1400598804016 2 connected 5461-10922";
HostAndPort current = new HostAndPort("localhost", 7379);
ClusterNodeInformation clusterNodeInfo = parser
.parse(nodeInfo, current);
assertNotEquals(clusterNodeInfo.getNode(), current);
assertEquals(clusterNodeInfo.getNode(), new HostAndPort("192.168.0.3",
7380));
for (int slot = 5461; slot <= 10922; slot++) {
assertTrue(clusterNodeInfo.getAvailableSlots().contains(slot));
}
for (int slot = 5461; slot <= 10922; slot++) {
assertTrue(clusterNodeInfo.getAvailableSlots().contains(slot));
}
assertTrue(clusterNodeInfo.getSlotsBeingImported().isEmpty());
assertTrue(clusterNodeInfo.getSlotsBeingMigrated().isEmpty());
assertTrue(clusterNodeInfo.getSlotsBeingImported().isEmpty());
assertTrue(clusterNodeInfo.getSlotsBeingMigrated().isEmpty());
}
@Test
public void testParseSlotBeingMigrated() {
String nodeInfo = "5f4a2236d00008fba7ac0dd24b95762b446767bd :7379 myself,master - 0 0 1 connected 0-5459 [5460->-5f4a2236d00008fba7ac0dd24b95762b446767bd] [5461-<-5f4a2236d00008fba7ac0dd24b95762b446767bd]";
HostAndPort current = new HostAndPort("localhost", 7379);
ClusterNodeInformation clusterNodeInfo = parser
.parse(nodeInfo, current);
assertEquals(clusterNodeInfo.getNode(), current);
String nodeInfo = "5f4a2236d00008fba7ac0dd24b95762b446767bd :7379 myself,master - 0 0 1 connected 0-5459 [5460->-5f4a2236d00008fba7ac0dd24b95762b446767bd] [5461-<-5f4a2236d00008fba7ac0dd24b95762b446767bd]";
HostAndPort current = new HostAndPort("localhost", 7379);
ClusterNodeInformation clusterNodeInfo = parser
.parse(nodeInfo, current);
assertEquals(clusterNodeInfo.getNode(), current);
for (int slot = 0; slot <= 5459; slot++) {
assertTrue(clusterNodeInfo.getAvailableSlots().contains(slot));
}
for (int slot = 0; slot <= 5459; slot++) {
assertTrue(clusterNodeInfo.getAvailableSlots().contains(slot));
}
assertEquals(1, clusterNodeInfo.getSlotsBeingMigrated().size());
assertTrue(clusterNodeInfo.getSlotsBeingMigrated().contains(5460));
assertEquals(1, clusterNodeInfo.getSlotsBeingImported().size());
assertTrue(clusterNodeInfo.getSlotsBeingImported().contains(5461));
assertEquals(1, clusterNodeInfo.getSlotsBeingMigrated().size());
assertTrue(clusterNodeInfo.getSlotsBeingMigrated().contains(5460));
assertEquals(1, clusterNodeInfo.getSlotsBeingImported().size());
assertTrue(clusterNodeInfo.getSlotsBeingImported().contains(5461));
}
}

View File

@@ -49,110 +49,110 @@ public class JedisClusterTest extends Assert {
@Before
public void setUp() throws InterruptedException {
node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort());
node1.connect();
node1.flushAll();
node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort());
node1.connect();
node1.flushAll();
node2 = new Jedis(nodeInfo2.getHost(), nodeInfo2.getPort());
node2.connect();
node2.flushAll();
node2 = new Jedis(nodeInfo2.getHost(), nodeInfo2.getPort());
node2.connect();
node2.flushAll();
node3 = new Jedis(nodeInfo3.getHost(), nodeInfo3.getPort());
node3.connect();
node3.flushAll();
node3 = new Jedis(nodeInfo3.getHost(), nodeInfo3.getPort());
node3.connect();
node3.flushAll();
node4 = new Jedis(nodeInfo4.getHost(), nodeInfo4.getPort());
node4.connect();
node4.flushAll();
node4 = new Jedis(nodeInfo4.getHost(), nodeInfo4.getPort());
node4.connect();
node4.flushAll();
// ---- configure cluster
// ---- configure cluster
// add nodes to cluster
node1.clusterMeet(localHost, nodeInfo2.getPort());
node1.clusterMeet(localHost, nodeInfo3.getPort());
// add nodes to cluster
node1.clusterMeet(localHost, nodeInfo2.getPort());
node1.clusterMeet(localHost, nodeInfo3.getPort());
// split available slots across the three nodes
int slotsPerNode = JedisCluster.HASHSLOTS / 3;
int[] node1Slots = new int[slotsPerNode];
int[] node2Slots = new int[slotsPerNode + 1];
int[] node3Slots = new int[slotsPerNode];
for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < JedisCluster.HASHSLOTS; i++) {
if (i < slotsPerNode) {
node1Slots[slot1++] = i;
} else if (i > slotsPerNode * 2) {
node3Slots[slot3++] = i;
} else {
node2Slots[slot2++] = i;
}
}
// split available slots across the three nodes
int slotsPerNode = JedisCluster.HASHSLOTS / 3;
int[] node1Slots = new int[slotsPerNode];
int[] node2Slots = new int[slotsPerNode + 1];
int[] node3Slots = new int[slotsPerNode];
for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < JedisCluster.HASHSLOTS; i++) {
if (i < slotsPerNode) {
node1Slots[slot1++] = i;
} else if (i > slotsPerNode * 2) {
node3Slots[slot3++] = i;
} else {
node2Slots[slot2++] = i;
}
}
node1.clusterAddSlots(node1Slots);
node2.clusterAddSlots(node2Slots);
node3.clusterAddSlots(node3Slots);
node1.clusterAddSlots(node1Slots);
node2.clusterAddSlots(node2Slots);
node3.clusterAddSlots(node3Slots);
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3);
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3);
}
@AfterClass
public static void cleanUp() {
node1.flushDB();
node2.flushDB();
node3.flushDB();
node4.flushDB();
node1.clusterReset(Reset.SOFT);
node2.clusterReset(Reset.SOFT);
node3.clusterReset(Reset.SOFT);
node4.clusterReset(Reset.SOFT);
node1.flushDB();
node2.flushDB();
node3.flushDB();
node4.flushDB();
node1.clusterReset(Reset.SOFT);
node2.clusterReset(Reset.SOFT);
node3.clusterReset(Reset.SOFT);
node4.clusterReset(Reset.SOFT);
}
@After
public void tearDown() throws InterruptedException {
cleanUp();
cleanUp();
}
@Test(expected = JedisMovedDataException.class)
public void testThrowMovedException() {
node1.set("foo", "bar");
node1.set("foo", "bar");
}
@Test
public void testMovedExceptionParameters() {
try {
node1.set("foo", "bar");
} catch (JedisMovedDataException jme) {
assertEquals(12182, jme.getSlot());
assertEquals(new HostAndPort("127.0.0.1", 7381),
jme.getTargetNode());
return;
}
fail();
try {
node1.set("foo", "bar");
} catch (JedisMovedDataException jme) {
assertEquals(12182, jme.getSlot());
assertEquals(new HostAndPort("127.0.0.1", 7381),
jme.getTargetNode());
return;
}
fail();
}
@Test(expected = JedisAskDataException.class)
public void testThrowAskException() {
int keySlot = JedisClusterCRC16.getSlot("test");
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
node2.clusterSetSlotMigrating(keySlot, node3Id);
node2.get("test");
int keySlot = JedisClusterCRC16.getSlot("test");
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
node2.clusterSetSlotMigrating(keySlot, node3Id);
node2.get("test");
}
@Test
public void testDiscoverNodesAutomatically() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
assertEquals(3, jc.getClusterNodes().size());
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
assertEquals(3, jc.getClusterNodes().size());
}
@Test
public void testCalculateConnectionPerSlot() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
jc.set("foo", "bar");
jc.set("test", "test");
assertEquals("bar", node3.get("foo"));
assertEquals("test", node2.get("test"));
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
jc.set("foo", "bar");
jc.set("test", "test");
assertEquals("bar", node3.get("foo"));
assertEquals("test", node2.get("test"));
}
/**
@@ -160,389 +160,389 @@ public class JedisClusterTest extends Assert {
*/
@Test
public void testMigrate() {
log.info("test migrate slot");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1);
JedisCluster jc = new JedisCluster(jedisClusterNode);
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
String node2Id = JedisClusterTestUtil.getNodeId(node2.clusterNodes());
node3.clusterSetSlotMigrating(15363, node2Id);
node2.clusterSetSlotImporting(15363, node3Id);
try {
node2.set("e", "e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
log.info("test migrate slot");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1);
JedisCluster jc = new JedisCluster(jedisClusterNode);
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
String node2Id = JedisClusterTestUtil.getNodeId(node2.clusterNodes());
node3.clusterSetSlotMigrating(15363, node2Id);
node2.clusterSetSlotImporting(15363, node3Id);
try {
node2.set("e", "e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
try {
node3.set("e", "e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()),
jae.getTargetNode());
}
try {
node3.set("e", "e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()),
jae.getTargetNode());
}
jc.set("e", "e");
jc.set("e", "e");
try {
node2.get("e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
try {
node3.get("e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()),
jae.getTargetNode());
}
try {
node2.get("e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
try {
node3.get("e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()),
jae.getTargetNode());
}
assertEquals("e", jc.get("e"));
assertEquals("e", jc.get("e"));
node2.clusterSetSlotNode(15363, node2Id);
node3.clusterSetSlotNode(15363, node2Id);
// assertEquals("e", jc.get("e"));
assertEquals("e", node2.get("e"));
node2.clusterSetSlotNode(15363, node2Id);
node3.clusterSetSlotNode(15363, node2Id);
// assertEquals("e", jc.get("e"));
assertEquals("e", node2.get("e"));
// assertEquals("e", node3.get("e"));
// assertEquals("e", node3.get("e"));
}
@Test
public void testMigrateToNewNode() throws InterruptedException {
log.info("test migrate slot to new node");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1);
JedisCluster jc = new JedisCluster(jedisClusterNode);
node4.clusterMeet(localHost, nodeInfo1.getPort());
log.info("test migrate slot to new node");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1);
JedisCluster jc = new JedisCluster(jedisClusterNode);
node4.clusterMeet(localHost, nodeInfo1.getPort());
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
String node4Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
JedisClusterTestUtil.waitForClusterReady(node4);
node3.clusterSetSlotMigrating(15363, node4Id);
node4.clusterSetSlotImporting(15363, node3Id);
try {
node4.set("e", "e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
String node4Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
JedisClusterTestUtil.waitForClusterReady(node4);
node3.clusterSetSlotMigrating(15363, node4Id);
node4.clusterSetSlotImporting(15363, node3Id);
try {
node4.set("e", "e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
try {
node3.set("e", "e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()),
jae.getTargetNode());
}
try {
node3.set("e", "e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()),
jae.getTargetNode());
}
jc.set("e", "e");
jc.set("e", "e");
try {
node4.get("e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
try {
node3.get("e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()),
jae.getTargetNode());
}
try {
node4.get("e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
try {
node3.get("e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()),
jae.getTargetNode());
}
assertEquals("e", jc.get("e"));
assertEquals("e", jc.get("e"));
node4.clusterSetSlotNode(15363, node4Id);
node3.clusterSetSlotNode(15363, node4Id);
// assertEquals("e", jc.get("e"));
assertEquals("e", node4.get("e"));
node4.clusterSetSlotNode(15363, node4Id);
node3.clusterSetSlotNode(15363, node4Id);
// assertEquals("e", jc.get("e"));
assertEquals("e", node4.get("e"));
// assertEquals("e", node3.get("e"));
// assertEquals("e", node3.get("e"));
}
@Test
public void testRecalculateSlotsWhenMoved() throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
int slot51 = JedisClusterCRC16.getSlot("51");
node2.clusterDelSlots(slot51);
node3.clusterDelSlots(slot51);
node3.clusterAddSlots(slot51);
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
int slot51 = JedisClusterCRC16.getSlot("51");
node2.clusterDelSlots(slot51);
node3.clusterDelSlots(slot51);
node3.clusterAddSlots(slot51);
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3);
jc.set("51", "foo");
assertEquals("foo", jc.get("51"));
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3);
jc.set("51", "foo");
assertEquals("foo", jc.get("51"));
}
@Test
public void testAskResponse() throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
int slot51 = JedisClusterCRC16.getSlot("51");
node3.clusterSetSlotImporting(slot51,
JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
node2.clusterSetSlotMigrating(slot51,
JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
jc.set("51", "foo");
assertEquals("foo", jc.get("51"));
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
int slot51 = JedisClusterCRC16.getSlot("51");
node3.clusterSetSlotImporting(slot51,
JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
node2.clusterSetSlotMigrating(slot51,
JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
jc.set("51", "foo");
assertEquals("foo", jc.get("51"));
}
@Test(expected = JedisClusterException.class)
public void testThrowExceptionWithoutKey() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
jc.ping();
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
jc.ping();
}
@Test(expected = JedisClusterMaxRedirectionsException.class)
public void testRedisClusterMaxRedirections() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
int slot51 = JedisClusterCRC16.getSlot("51");
// This will cause an infinite redirection loop
node2.clusterSetSlotMigrating(slot51,
JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
jc.set("51", "foo");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
int slot51 = JedisClusterCRC16.getSlot("51");
// This will cause an infinite redirection loop
node2.clusterSetSlotMigrating(slot51,
JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
jc.set("51", "foo");
}
@Test
public void testRedisHashtag() {
assertEquals(JedisClusterCRC16.getSlot("{bar"),
JedisClusterCRC16.getSlot("foo{{bar}}zap"));
assertEquals(JedisClusterCRC16.getSlot("{user1000}.following"),
JedisClusterCRC16.getSlot("{user1000}.followers"));
assertNotEquals(JedisClusterCRC16.getSlot("foo{}{bar}"),
JedisClusterCRC16.getSlot("bar"));
assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"),
JedisClusterCRC16.getSlot("bar"));
assertEquals(JedisClusterCRC16.getSlot("{bar"),
JedisClusterCRC16.getSlot("foo{{bar}}zap"));
assertEquals(JedisClusterCRC16.getSlot("{user1000}.following"),
JedisClusterCRC16.getSlot("{user1000}.followers"));
assertNotEquals(JedisClusterCRC16.getSlot("foo{}{bar}"),
JedisClusterCRC16.getSlot("bar"));
assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"),
JedisClusterCRC16.getSlot("bar"));
}
@Test
public void testClusterForgetNode() throws InterruptedException {
// at first, join node4 to cluster
node1.clusterMeet("127.0.0.1", nodeInfo4.getPort());
// at first, join node4 to cluster
node1.clusterMeet("127.0.0.1", nodeInfo4.getPort());
String node7Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
String node7Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
JedisClusterTestUtil.assertNodeIsKnown(node3, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node1, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node3, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node1, node7Id, 1000);
assertNodeHandshakeEnded(node3, 1000);
assertNodeHandshakeEnded(node2, 1000);
assertNodeHandshakeEnded(node1, 1000);
assertNodeHandshakeEnded(node3, 1000);
assertNodeHandshakeEnded(node2, 1000);
assertNodeHandshakeEnded(node1, 1000);
assertEquals(4, node1.clusterNodes().split("\n").length);
assertEquals(4, node2.clusterNodes().split("\n").length);
assertEquals(4, node3.clusterNodes().split("\n").length);
assertEquals(4, node1.clusterNodes().split("\n").length);
assertEquals(4, node2.clusterNodes().split("\n").length);
assertEquals(4, node3.clusterNodes().split("\n").length);
// do cluster forget
node1.clusterForget(node7Id);
node2.clusterForget(node7Id);
node3.clusterForget(node7Id);
// do cluster forget
node1.clusterForget(node7Id);
node2.clusterForget(node7Id);
node3.clusterForget(node7Id);
JedisClusterTestUtil.assertNodeIsUnknown(node1, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node3, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node1, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node3, node7Id, 1000);
assertEquals(3, node1.clusterNodes().split("\n").length);
assertEquals(3, node2.clusterNodes().split("\n").length);
assertEquals(3, node3.clusterNodes().split("\n").length);
assertEquals(3, node1.clusterNodes().split("\n").length);
assertEquals(3, node2.clusterNodes().split("\n").length);
assertEquals(3, node3.clusterNodes().split("\n").length);
}
@Test
public void testClusterFlushSlots() {
String slotRange = getNodeServingSlotRange(node1.clusterNodes());
assertNotNull(slotRange);
String slotRange = getNodeServingSlotRange(node1.clusterNodes());
assertNotNull(slotRange);
try {
node1.clusterFlushSlots();
assertNull(getNodeServingSlotRange(node1.clusterNodes()));
} finally {
// rollback
String[] rangeInfo = slotRange.split("-");
int lower = Integer.parseInt(rangeInfo[0]);
int upper = Integer.parseInt(rangeInfo[1]);
try {
node1.clusterFlushSlots();
assertNull(getNodeServingSlotRange(node1.clusterNodes()));
} finally {
// rollback
String[] rangeInfo = slotRange.split("-");
int lower = Integer.parseInt(rangeInfo[0]);
int upper = Integer.parseInt(rangeInfo[1]);
int[] node1Slots = new int[upper - lower + 1];
for (int i = 0; lower <= upper;) {
node1Slots[i++] = lower++;
}
node1.clusterAddSlots(node1Slots);
}
int[] node1Slots = new int[upper - lower + 1];
for (int i = 0; lower <= upper;) {
node1Slots[i++] = lower++;
}
node1.clusterAddSlots(node1Slots);
}
}
@Test
public void testClusterKeySlot() {
// It assumes JedisClusterCRC16 is correctly implemented
assertEquals(node1.clusterKeySlot("foo{bar}zap}").intValue(),
JedisClusterCRC16.getSlot("foo{bar}zap"));
assertEquals(node1.clusterKeySlot("{user1000}.following").intValue(),
JedisClusterCRC16.getSlot("{user1000}.following"));
// It assumes JedisClusterCRC16 is correctly implemented
assertEquals(node1.clusterKeySlot("foo{bar}zap}").intValue(),
JedisClusterCRC16.getSlot("foo{bar}zap"));
assertEquals(node1.clusterKeySlot("{user1000}.following").intValue(),
JedisClusterCRC16.getSlot("{user1000}.following"));
}
@Test
public void testClusterCountKeysInSlot() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode);
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode);
for (int index = 0; index < 5; index++) {
jc.set("foo{bar}" + index, "hello");
}
for (int index = 0; index < 5; index++) {
jc.set("foo{bar}" + index, "hello");
}
int slot = JedisClusterCRC16.getSlot("foo{bar}");
assertEquals(5, node1.clusterCountKeysInSlot(slot).intValue());
int slot = JedisClusterCRC16.getSlot("foo{bar}");
assertEquals(5, node1.clusterCountKeysInSlot(slot).intValue());
}
@Test
public void testStableSlotWhenMigratingNodeOrImportingNodeIsNotSpecified()
throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode);
throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode);
int slot51 = JedisClusterCRC16.getSlot("51");
jc.set("51", "foo");
// node2 is responsible of taking care of slot51 (7186)
int slot51 = JedisClusterCRC16.getSlot("51");
jc.set("51", "foo");
// node2 is responsible of taking care of slot51 (7186)
node3.clusterSetSlotImporting(slot51,
JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
assertEquals("foo", jc.get("51"));
node3.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51"));
node3.clusterSetSlotImporting(slot51,
JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
assertEquals("foo", jc.get("51"));
node3.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51"));
node2.clusterSetSlotMigrating(slot51,
JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
// assertEquals("foo", jc.get("51")); // it leads Max Redirections
node2.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51"));
node2.clusterSetSlotMigrating(slot51,
JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
// assertEquals("foo", jc.get("51")); // it leads Max Redirections
node2.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51"));
}
@Test(expected = JedisConnectionException.class)
public void testIfPoolConfigAppliesToClusterPools() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(0);
config.setMaxWaitMillis(2000);
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, config);
jc.set("52", "poolTestValue");
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(0);
config.setMaxWaitMillis(2000);
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, config);
jc.set("52", "poolTestValue");
}
@Test
public void testCloseable() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
JedisCluster jc = null;
try {
jc = new JedisCluster(jedisClusterNode);
jc.set("51", "foo");
} finally {
if (jc != null) {
jc.close();
}
}
JedisCluster jc = null;
try {
jc = new JedisCluster(jedisClusterNode);
jc.set("51", "foo");
} finally {
if (jc != null) {
jc.close();
}
}
Iterator<JedisPool> poolIterator = jc.getClusterNodes().values()
.iterator();
while (poolIterator.hasNext()) {
JedisPool pool = poolIterator.next();
try {
pool.getResource();
fail("JedisCluster's internal pools should be already destroyed");
} catch (JedisConnectionException e) {
// ok to go...
}
}
Iterator<JedisPool> poolIterator = jc.getClusterNodes().values()
.iterator();
while (poolIterator.hasNext()) {
JedisPool pool = poolIterator.next();
try {
pool.getResource();
fail("JedisCluster's internal pools should be already destroyed");
} catch (JedisConnectionException e) {
// ok to go...
}
}
}
@Test
public void testJedisClusterRunsWithMultithreaded()
throws InterruptedException, ExecutionException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
final JedisCluster jc = new JedisCluster(jedisClusterNode);
jc.set("foo", "bar");
throws InterruptedException, ExecutionException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
final JedisCluster jc = new JedisCluster(jedisClusterNode);
jc.set("foo", "bar");
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 0,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
List<Future<String>> futures = new ArrayList<Future<String>>();
for (int i = 0; i < 50; i++) {
executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// FIXME : invalidate slot cache from JedisCluster to test
// random connection also does work
return jc.get("foo");
}
});
}
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 0,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
List<Future<String>> futures = new ArrayList<Future<String>>();
for (int i = 0; i < 50; i++) {
executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// FIXME : invalidate slot cache from JedisCluster to test
// random connection also does work
return jc.get("foo");
}
});
}
for (Future<String> future : futures) {
String value = future.get();
assertEquals("bar", value);
}
for (Future<String> future : futures) {
String value = future.get();
assertEquals("bar", value);
}
jc.close();
jc.close();
}
private static String getNodeServingSlotRange(String infoOutput) {
// f4f3dc4befda352a4e0beccf29f5e8828438705d 127.0.0.1:7380 master - 0
// 1394372400827 0 connected 5461-10922
for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("myself")) {
try {
return infoLine.split(" ")[8];
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
}
}
return null;
// f4f3dc4befda352a4e0beccf29f5e8828438705d 127.0.0.1:7380 master - 0
// 1394372400827 0 connected 5461-10922
for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("myself")) {
try {
return infoLine.split(" ")[8];
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
}
}
return null;
}
private void assertNodeHandshakeEnded(Jedis node, int timeoutMs) {
int sleepInterval = 100;
for (int sleepTime = 0; sleepTime <= timeoutMs; sleepTime += sleepInterval) {
boolean isHandshaking = isAnyNodeHandshaking(node);
if (!isHandshaking)
return;
int sleepInterval = 100;
for (int sleepTime = 0; sleepTime <= timeoutMs; sleepTime += sleepInterval) {
boolean isHandshaking = isAnyNodeHandshaking(node);
if (!isHandshaking)
return;
try {
Thread.sleep(sleepInterval);
} catch (InterruptedException e) {
}
}
try {
Thread.sleep(sleepInterval);
} catch (InterruptedException e) {
}
}
throw new JedisException("Node handshaking is not ended");
throw new JedisException("Node handshaking is not ended");
}
private boolean isAnyNodeHandshaking(Jedis node) {
String infoOutput = node.clusterNodes();
for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("handshake")) {
return true;
}
}
return false;
String infoOutput = node.clusterNodes();
for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("handshake")) {
return true;
}
}
return false;
}
}

View File

@@ -1,8 +1,13 @@
package redis.clients.jedis.tests;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.junit.Assert;
import org.junit.Test;
@@ -19,288 +24,338 @@ public class JedisPoolTest extends Assert {
@Test
public void checkConnections() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000);
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000);
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
}
@Test
public void checkCloseableConnections() throws Exception {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000);
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.close();
assertTrue(pool.isClosed());
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000);
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.close();
assertTrue(pool.isClosed());
}
@Test
public void checkConnectionWithDefaultPort() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort());
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort());
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
}
@Test
public void checkJedisIsReusedWhenReturned() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort());
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "0");
pool.returnResource(jedis);
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort());
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "0");
pool.returnResource(jedis);
jedis = pool.getResource();
jedis.auth("foobared");
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
jedis = pool.getResource();
jedis.auth("foobared");
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
}
@Test
public void checkPoolRepairedWhenJedisIsBroken() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort());
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.quit();
pool.returnBrokenResource(jedis);
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort());
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.quit();
pool.returnBrokenResource(jedis);
jedis = pool.getResource();
jedis.auth("foobared");
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
jedis = pool.getResource();
jedis.auth("foobared");
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
}
@Test(expected = JedisConnectionException.class)
public void checkPoolOverflow() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort());
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "0");
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort());
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "0");
Jedis newJedis = pool.getResource();
newJedis.auth("foobared");
newJedis.incr("foo");
Jedis newJedis = pool.getResource();
newJedis.auth("foobared");
newJedis.incr("foo");
}
@Test
public void securePool() {
JedisPoolConfig config = new JedisPoolConfig();
config.setTestOnBorrow(true);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(),
2000, "foobared");
Jedis jedis = pool.getResource();
jedis.set("foo", "bar");
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
JedisPoolConfig config = new JedisPoolConfig();
config.setTestOnBorrow(true);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(),
2000, "foobared");
Jedis jedis = pool.getResource();
jedis.set("foo", "bar");
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
}
@Test
public void nonDefaultDatabase() {
JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared");
Jedis jedis0 = pool0.getResource();
jedis0.set("foo", "bar");
assertEquals("bar", jedis0.get("foo"));
pool0.returnResource(jedis0);
pool0.destroy();
assertTrue(pool0.isClosed());
JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared");
Jedis jedis0 = pool0.getResource();
jedis0.set("foo", "bar");
assertEquals("bar", jedis0.get("foo"));
pool0.returnResource(jedis0);
pool0.destroy();
assertTrue(pool0.isClosed());
JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared", 1);
Jedis jedis1 = pool1.getResource();
assertNull(jedis1.get("foo"));
pool1.returnResource(jedis1);
pool1.destroy();
assertTrue(pool1.isClosed());
JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared", 1);
Jedis jedis1 = pool1.getResource();
assertNull(jedis1.get("foo"));
pool1.returnResource(jedis1);
pool1.destroy();
assertTrue(pool1.isClosed());
}
@Test
public void startWithUrlString() {
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
JedisPool pool = new JedisPool("redis://:foobared@localhost:6380/2");
Jedis jedis = pool.getResource();
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
JedisPool pool = new JedisPool("redis://:foobared@localhost:6380/2");
Jedis jedis = pool.getResource();
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
}
@Test
public void startWithUrl() throws URISyntaxException {
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
JedisPool pool = new JedisPool(new URI(
"redis://:foobared@localhost:6380/2"));
Jedis jedis = pool.getResource();
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
JedisPool pool = new JedisPool(new URI(
"redis://:foobared@localhost:6380/2"));
Jedis jedis = pool.getResource();
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
}
@Test
public void allowUrlWithNoDBAndNoPassword() throws URISyntaxException {
new JedisPool("redis://localhost:6380");
new JedisPool(new URI("redis://localhost:6380"));
new JedisPool("redis://localhost:6380");
new JedisPool(new URI("redis://localhost:6380"));
}
@Test
public void selectDatabaseOnActivation() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared");
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared");
Jedis jedis0 = pool.getResource();
assertEquals(0L, jedis0.getDB().longValue());
Jedis jedis0 = pool.getResource();
assertEquals(0L, jedis0.getDB().longValue());
jedis0.select(1);
assertEquals(1L, jedis0.getDB().longValue());
jedis0.select(1);
assertEquals(1L, jedis0.getDB().longValue());
pool.returnResource(jedis0);
pool.returnResource(jedis0);
Jedis jedis1 = pool.getResource();
assertTrue("Jedis instance was not reused", jedis1 == jedis0);
assertEquals(0L, jedis1.getDB().longValue());
Jedis jedis1 = pool.getResource();
assertTrue("Jedis instance was not reused", jedis1 == jedis0);
assertEquals(0L, jedis1.getDB().longValue());
pool.returnResource(jedis1);
pool.destroy();
assertTrue(pool.isClosed());
pool.returnResource(jedis1);
pool.destroy();
assertTrue(pool.isClosed());
}
@Test
public void customClientName() {
JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name");
JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name");
Jedis jedis = pool0.getResource();
Jedis jedis = pool0.getResource();
assertEquals("my_shiny_client_name", jedis.clientGetname());
assertEquals("my_shiny_client_name", jedis.clientGetname());
pool0.returnResource(jedis);
pool0.destroy();
assertTrue(pool0.isClosed());
pool0.returnResource(jedis);
pool0.destroy();
assertTrue(pool0.isClosed());
}
@Test
public void returnResourceDestroysResourceOnException() {
class CrashingJedis extends Jedis {
@Override
public void resetState() {
throw new RuntimeException();
}
}
final AtomicInteger destroyed = new AtomicInteger(0);
class CrashingJedisPooledObjectFactory implements PooledObjectFactory<Jedis> {
@Override
public PooledObject<Jedis> makeObject() throws Exception {
return new DefaultPooledObject<Jedis>(new CrashingJedis());
}
@Override
public void destroyObject(PooledObject<Jedis> p) throws Exception {
destroyed.incrementAndGet();
}
@Override
public boolean validateObject(PooledObject<Jedis> p) {
return true;
}
@Override
public void activateObject(PooledObject<Jedis> p) throws Exception {}
@Override
public void passivateObject(PooledObject<Jedis> p) throws Exception {}
}
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "foobared");
pool.initPool(config, new CrashingJedisPooledObjectFactory());
Jedis crashingJedis = pool.getResource();
try {
pool.returnResource(crashingJedis);
}
catch (Exception ignored) {}
assertEquals(destroyed.get(), 1);
}
@Test
public void returnResourceShouldResetState() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(),
2000, "foobared");
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(),
2000, "foobared");
Jedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
Transaction t = jedis.multi();
t.set("hello", "world");
} finally {
jedis.close();
}
Jedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
Transaction t = jedis.multi();
t.set("hello", "world");
} finally {
jedis.close();
}
Jedis jedis2 = pool.getResource();
try {
assertTrue(jedis == jedis2);
assertEquals("jedis", jedis2.get("hello"));
} finally {
jedis2.close();
}
Jedis jedis2 = pool.getResource();
try {
assertTrue(jedis == jedis2);
assertEquals("jedis", jedis2.get("hello"));
} finally {
jedis2.close();
}
pool.destroy();
assertTrue(pool.isClosed());
pool.destroy();
assertTrue(pool.isClosed());
}
@Test
public void checkResourceIsCloseable() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(),
2000, "foobared");
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(),
2000, "foobared");
Jedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
} finally {
jedis.close();
}
Jedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
} finally {
jedis.close();
}
Jedis jedis2 = pool.getResource();
try {
assertEquals(jedis, jedis2);
} finally {
jedis2.close();
}
Jedis jedis2 = pool.getResource();
try {
assertEquals(jedis, jedis2);
} finally {
jedis2.close();
}
}
@Test
public void returnNullObjectShouldNotFail() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name");
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name");
pool.returnBrokenResource(null);
pool.returnResource(null);
pool.returnResourceObject(null);
pool.returnBrokenResource(null);
pool.returnResource(null);
pool.returnResourceObject(null);
}
@Test
public void getNumActiveIsNegativeWhenPoolIsClosed() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name");
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name");
pool.destroy();
assertTrue(pool.getNumActive() < 0);
pool.destroy();
assertTrue(pool.getNumActive() < 0);
}
@Test
public void getNumActiveReturnsTheCorrectNumber() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000);
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000);
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
assertEquals(1, pool.getNumActive());
assertEquals(1, pool.getNumActive());
Jedis jedis2 = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
Jedis jedis2 = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals(2, pool.getNumActive());
assertEquals(2, pool.getNumActive());
pool.returnResource(jedis);
assertEquals(1, pool.getNumActive());
pool.returnResource(jedis);
assertEquals(1, pool.getNumActive());
pool.returnResource(jedis2);
pool.returnResource(jedis2);
assertEquals(0, pool.getNumActive());
assertEquals(0, pool.getNumActive());
pool.destroy();
pool.destroy();
}
}

View File

@@ -19,14 +19,14 @@ public class JedisSentinelPoolTest extends JedisTestBase {
private static final String MASTER_NAME = "mymaster";
protected static HostAndPort master = HostAndPortUtil.getRedisServers()
.get(2);
.get(2);
protected static HostAndPort slave1 = HostAndPortUtil.getRedisServers()
.get(3);
.get(3);
protected static HostAndPort sentinel1 = HostAndPortUtil
.getSentinelServers().get(1);
.getSentinelServers().get(1);
protected static HostAndPort sentinel2 = HostAndPortUtil
.getSentinelServers().get(3);
.getSentinelServers().get(3);
protected static Jedis sentinelJedis1;
protected static Jedis sentinelJedis2;
@@ -35,188 +35,188 @@ public class JedisSentinelPoolTest extends JedisTestBase {
@Before
public void setUp() throws Exception {
sentinels.add(sentinel1.toString());
sentinels.add(sentinel2.toString());
sentinels.add(sentinel1.toString());
sentinels.add(sentinel2.toString());
sentinelJedis1 = new Jedis(sentinel1.getHost(), sentinel1.getPort());
sentinelJedis2 = new Jedis(sentinel2.getHost(), sentinel2.getPort());
sentinelJedis1 = new Jedis(sentinel1.getHost(), sentinel1.getPort());
sentinelJedis2 = new Jedis(sentinel2.getHost(), sentinel2.getPort());
}
@Test(expected = JedisConnectionException.class)
public void initializeWithNotAvailableSentinelsShouldThrowException() {
Set<String> wrongSentinels = new HashSet<String>();
wrongSentinels.add(new HostAndPort("localhost", 65432).toString());
wrongSentinels.add(new HostAndPort("localhost", 65431).toString());
Set<String> wrongSentinels = new HashSet<String>();
wrongSentinels.add(new HostAndPort("localhost", 65432).toString());
wrongSentinels.add(new HostAndPort("localhost", 65431).toString());
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME,
wrongSentinels);
pool.destroy();
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME,
wrongSentinels);
pool.destroy();
}
@Test(expected = JedisException.class)
public void initializeWithNotMonitoredMasterNameShouldThrowException() {
final String wrongMasterName = "wrongMasterName";
JedisSentinelPool pool = new JedisSentinelPool(wrongMasterName,
sentinels);
pool.destroy();
final String wrongMasterName = "wrongMasterName";
JedisSentinelPool pool = new JedisSentinelPool(wrongMasterName,
sentinels);
pool.destroy();
}
@Test
public void checkCloseableConnections() throws Exception {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.close();
assertTrue(pool.isClosed());
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.close();
assertTrue(pool.isClosed());
}
@Test
public void ensureSafeTwiceFailover() throws InterruptedException {
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
new GenericObjectPoolConfig(), 1000, "foobared", 2);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
new GenericObjectPoolConfig(), 1000, "foobared", 2);
forceFailover(pool);
// after failover sentinel needs a bit of time to stabilize before a new
// failover
Thread.sleep(100);
forceFailover(pool);
forceFailover(pool);
// after failover sentinel needs a bit of time to stabilize before a new
// failover
Thread.sleep(100);
forceFailover(pool);
// you can test failover as much as possible
// you can test failover as much as possible
}
@Test
public void returnResourceShouldResetState() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis jedis = pool.getResource();
Jedis jedis2 = null;
Jedis jedis = pool.getResource();
Jedis jedis2 = null;
try {
jedis.set("hello", "jedis");
Transaction t = jedis.multi();
t.set("hello", "world");
pool.returnResource(jedis);
try {
jedis.set("hello", "jedis");
Transaction t = jedis.multi();
t.set("hello", "world");
pool.returnResource(jedis);
jedis2 = pool.getResource();
jedis2 = pool.getResource();
assertTrue(jedis == jedis2);
assertEquals("jedis", jedis2.get("hello"));
} catch (JedisConnectionException e) {
if (jedis2 != null) {
pool.returnBrokenResource(jedis2);
jedis2 = null;
}
} finally {
if (jedis2 != null)
pool.returnResource(jedis2);
assertTrue(jedis == jedis2);
assertEquals("jedis", jedis2.get("hello"));
} catch (JedisConnectionException e) {
if (jedis2 != null) {
pool.returnBrokenResource(jedis2);
jedis2 = null;
}
} finally {
if (jedis2 != null)
pool.returnResource(jedis2);
pool.destroy();
}
pool.destroy();
}
}
@Test
public void checkResourceIsCloseable() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
} finally {
jedis.close();
}
Jedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
} finally {
jedis.close();
}
Jedis jedis2 = pool.getResource();
try {
assertEquals(jedis, jedis2);
} finally {
jedis2.close();
}
Jedis jedis2 = pool.getResource();
try {
assertEquals(jedis, jedis2);
} finally {
jedis2.close();
}
}
@Test
public void returnResourceWithNullResource() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis nullJedis = null;
pool.returnResource(nullJedis);
pool.destroy();
Jedis nullJedis = null;
pool.returnResource(nullJedis);
pool.destroy();
}
@Test
public void returnBrokenResourceWithNullResource() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis nullJedis = null;
pool.returnBrokenResource(nullJedis);
pool.destroy();
Jedis nullJedis = null;
pool.returnBrokenResource(nullJedis);
pool.destroy();
}
private void forceFailover(JedisSentinelPool pool)
throws InterruptedException {
HostAndPort oldMaster = pool.getCurrentHostMaster();
throws InterruptedException {
HostAndPort oldMaster = pool.getCurrentHostMaster();
// jedis connection should be master
Jedis beforeFailoverJedis = pool.getResource();
assertEquals("PONG", beforeFailoverJedis.ping());
// jedis connection should be master
Jedis beforeFailoverJedis = pool.getResource();
assertEquals("PONG", beforeFailoverJedis.ping());
waitForFailover(pool, oldMaster);
waitForFailover(pool, oldMaster);
Jedis afterFailoverJedis = pool.getResource();
assertEquals("PONG", afterFailoverJedis.ping());
assertEquals("foobared", afterFailoverJedis.configGet("requirepass")
.get(1));
assertEquals(2, afterFailoverJedis.getDB().intValue());
Jedis afterFailoverJedis = pool.getResource();
assertEquals("PONG", afterFailoverJedis.ping());
assertEquals("foobared", afterFailoverJedis.configGet("requirepass")
.get(1));
assertEquals(2, afterFailoverJedis.getDB().intValue());
// returning both connections to the pool should not throw
beforeFailoverJedis.close();
afterFailoverJedis.close();
// returning both connections to the pool should not throw
beforeFailoverJedis.close();
afterFailoverJedis.close();
}
private void waitForFailover(JedisSentinelPool pool, HostAndPort oldMaster)
throws InterruptedException {
HostAndPort newMaster = JedisSentinelTestUtil.waitForNewPromotedMaster(
MASTER_NAME, sentinelJedis1, sentinelJedis2);
throws InterruptedException {
HostAndPort newMaster = JedisSentinelTestUtil.waitForNewPromotedMaster(
MASTER_NAME, sentinelJedis1, sentinelJedis2);
waitForJedisSentinelPoolRecognizeNewMaster(pool, newMaster);
waitForJedisSentinelPoolRecognizeNewMaster(pool, newMaster);
}
private void waitForJedisSentinelPoolRecognizeNewMaster(
JedisSentinelPool pool, HostAndPort newMaster)
throws InterruptedException {
JedisSentinelPool pool, HostAndPort newMaster)
throws InterruptedException {
while (true) {
HostAndPort currentHostMaster = pool.getCurrentHostMaster();
while (true) {
HostAndPort currentHostMaster = pool.getCurrentHostMaster();
if (newMaster.equals(currentHostMaster))
break;
if (newMaster.equals(currentHostMaster))
break;
System.out
.println("JedisSentinelPool's master is not yet changed, sleep...");
System.out
.println("JedisSentinelPool's master is not yet changed, sleep...");
Thread.sleep(100);
}
Thread.sleep(100);
}
}
}

View File

@@ -21,16 +21,16 @@ public class JedisSentinelTest extends JedisTestBase {
private static final String MASTER_IP = "127.0.0.1";
protected static HostAndPort master = HostAndPortUtil.getRedisServers()
.get(0);
.get(0);
protected static HostAndPort slave = HostAndPortUtil.getRedisServers().get(
4);
4);
protected static HostAndPort sentinel = HostAndPortUtil
.getSentinelServers().get(0);
.getSentinelServers().get(0);
protected static HostAndPort sentinelForFailover = HostAndPortUtil
.getSentinelServers().get(2);
.getSentinelServers().get(2);
protected static HostAndPort masterForFailover = HostAndPortUtil
.getRedisServers().get(5);
.getRedisServers().get(5);
@Before
public void setup() throws InterruptedException {
@@ -38,173 +38,173 @@ public class JedisSentinelTest extends JedisTestBase {
@After
public void clear() throws InterruptedException {
// New Sentinel (after 2.8.1)
// when slave promoted to master (slave of no one), New Sentinel force
// to restore it (demote)
// so, promote(slaveof) slave to master has no effect, not same to old
// Sentinel's behavior
ensureRemoved(MONITOR_MASTER_NAME);
ensureRemoved(REMOVE_MASTER_NAME);
// New Sentinel (after 2.8.1)
// when slave promoted to master (slave of no one), New Sentinel force
// to restore it (demote)
// so, promote(slaveof) slave to master has no effect, not same to old
// Sentinel's behavior
ensureRemoved(MONITOR_MASTER_NAME);
ensureRemoved(REMOVE_MASTER_NAME);
}
@Test
public void sentinel() {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
List<Map<String, String>> masters = j.sentinelMasters();
try {
List<Map<String, String>> masters = j.sentinelMasters();
boolean inMasters = false;
for (Map<String, String> master : masters)
if (MASTER_NAME.equals(master.get("name")))
inMasters = true;
boolean inMasters = false;
for (Map<String, String> master : masters)
if (MASTER_NAME.equals(master.get("name")))
inMasters = true;
assertTrue(inMasters);
assertTrue(inMasters);
List<String> masterHostAndPort = j
.sentinelGetMasterAddrByName(MASTER_NAME);
HostAndPort masterFromSentinel = new HostAndPort(
masterHostAndPort.get(0),
Integer.parseInt(masterHostAndPort.get(1)));
assertEquals(master, masterFromSentinel);
List<String> masterHostAndPort = j
.sentinelGetMasterAddrByName(MASTER_NAME);
HostAndPort masterFromSentinel = new HostAndPort(
masterHostAndPort.get(0),
Integer.parseInt(masterHostAndPort.get(1)));
assertEquals(master, masterFromSentinel);
List<Map<String, String>> slaves = j.sentinelSlaves(MASTER_NAME);
assertTrue(slaves.size() > 0);
assertEquals(master.getPort(),
Integer.parseInt(slaves.get(0).get("master-port")));
List<Map<String, String>> slaves = j.sentinelSlaves(MASTER_NAME);
assertTrue(slaves.size() > 0);
assertEquals(master.getPort(),
Integer.parseInt(slaves.get(0).get("master-port")));
// DO NOT RE-RUN TEST TOO FAST, RESET TAKES SOME TIME TO... RESET
assertEquals(Long.valueOf(1), j.sentinelReset(MASTER_NAME));
assertEquals(Long.valueOf(0), j.sentinelReset("woof" + MASTER_NAME));
} finally {
j.close();
}
// DO NOT RE-RUN TEST TOO FAST, RESET TAKES SOME TIME TO... RESET
assertEquals(Long.valueOf(1), j.sentinelReset(MASTER_NAME));
assertEquals(Long.valueOf(0), j.sentinelReset("woof" + MASTER_NAME));
} finally {
j.close();
}
}
@Test
public void sentinelFailover() throws InterruptedException {
Jedis j = new Jedis(sentinelForFailover.getHost(),
sentinelForFailover.getPort());
Jedis j2 = new Jedis(sentinelForFailover.getHost(),
sentinelForFailover.getPort());
Jedis j = new Jedis(sentinelForFailover.getHost(),
sentinelForFailover.getPort());
Jedis j2 = new Jedis(sentinelForFailover.getHost(),
sentinelForFailover.getPort());
try {
List<String> masterHostAndPort = j
.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME);
HostAndPort currentMaster = new HostAndPort(
masterHostAndPort.get(0),
Integer.parseInt(masterHostAndPort.get(1)));
try {
List<String> masterHostAndPort = j
.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME);
HostAndPort currentMaster = new HostAndPort(
masterHostAndPort.get(0),
Integer.parseInt(masterHostAndPort.get(1)));
JedisSentinelTestUtil.waitForNewPromotedMaster(
FAILOVER_MASTER_NAME, j, j2);
JedisSentinelTestUtil.waitForNewPromotedMaster(
FAILOVER_MASTER_NAME, j, j2);
masterHostAndPort = j
.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME);
HostAndPort newMaster = new HostAndPort(masterHostAndPort.get(0),
Integer.parseInt(masterHostAndPort.get(1)));
masterHostAndPort = j
.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME);
HostAndPort newMaster = new HostAndPort(masterHostAndPort.get(0),
Integer.parseInt(masterHostAndPort.get(1)));
assertNotEquals(newMaster, currentMaster);
} finally {
j.close();
}
assertNotEquals(newMaster, currentMaster);
} finally {
j.close();
}
}
@Test
public void sentinelMonitor() {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
// monitor new master
String result = j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP,
master.getPort(), 1);
assertEquals("OK", result);
try {
// monitor new master
String result = j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP,
master.getPort(), 1);
assertEquals("OK", result);
// already monitored
try {
j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP,
master.getPort(), 1);
fail();
} catch (JedisDataException e) {
// pass
}
} finally {
j.close();
}
// already monitored
try {
j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP,
master.getPort(), 1);
fail();
} catch (JedisDataException e) {
// pass
}
} finally {
j.close();
}
}
@Test
public void sentinelRemove() {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
ensureMonitored(sentinel, REMOVE_MASTER_NAME, MASTER_IP,
master.getPort(), 1);
try {
ensureMonitored(sentinel, REMOVE_MASTER_NAME, MASTER_IP,
master.getPort(), 1);
String result = j.sentinelRemove(REMOVE_MASTER_NAME);
assertEquals("OK", result);
String result = j.sentinelRemove(REMOVE_MASTER_NAME);
assertEquals("OK", result);
// not exist
try {
result = j.sentinelRemove(REMOVE_MASTER_NAME);
assertNotEquals("OK", result);
fail();
} catch (JedisDataException e) {
// pass
}
} finally {
j.close();
}
// not exist
try {
result = j.sentinelRemove(REMOVE_MASTER_NAME);
assertNotEquals("OK", result);
fail();
} catch (JedisDataException e) {
// pass
}
} finally {
j.close();
}
}
@Test
public void sentinelSet() {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
Map<String, String> parameterMap = new HashMap<String, String>();
parameterMap.put("down-after-milliseconds", String.valueOf(1234));
parameterMap.put("parallel-syncs", String.valueOf(3));
parameterMap.put("quorum", String.valueOf(2));
j.sentinelSet(MASTER_NAME, parameterMap);
try {
Map<String, String> parameterMap = new HashMap<String, String>();
parameterMap.put("down-after-milliseconds", String.valueOf(1234));
parameterMap.put("parallel-syncs", String.valueOf(3));
parameterMap.put("quorum", String.valueOf(2));
j.sentinelSet(MASTER_NAME, parameterMap);
List<Map<String, String>> masters = j.sentinelMasters();
for (Map<String, String> master : masters) {
if (master.get("name").equals(MASTER_NAME)) {
assertEquals(1234, Integer.parseInt(master
.get("down-after-milliseconds")));
assertEquals(3,
Integer.parseInt(master.get("parallel-syncs")));
assertEquals(2, Integer.parseInt(master.get("quorum")));
}
}
List<Map<String, String>> masters = j.sentinelMasters();
for (Map<String, String> master : masters) {
if (master.get("name").equals(MASTER_NAME)) {
assertEquals(1234, Integer.parseInt(master
.get("down-after-milliseconds")));
assertEquals(3,
Integer.parseInt(master.get("parallel-syncs")));
assertEquals(2, Integer.parseInt(master.get("quorum")));
}
}
parameterMap.put("quorum", String.valueOf(1));
j.sentinelSet(MASTER_NAME, parameterMap);
} finally {
j.close();
}
parameterMap.put("quorum", String.valueOf(1));
j.sentinelSet(MASTER_NAME, parameterMap);
} finally {
j.close();
}
}
private void ensureMonitored(HostAndPort sentinel, String masterName,
String ip, int port, int quorum) {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
j.sentinelMonitor(masterName, ip, port, quorum);
} catch (JedisDataException e) {
} finally {
j.close();
}
String ip, int port, int quorum) {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
j.sentinelMonitor(masterName, ip, port, quorum);
} catch (JedisDataException e) {
} finally {
j.close();
}
}
private void ensureRemoved(String masterName) {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
j.sentinelRemove(masterName);
} catch (JedisDataException e) {
} finally {
j.close();
}
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
j.sentinelRemove(masterName);
} catch (JedisDataException e) {
} finally {
j.close();
}
}
}

View File

@@ -20,107 +20,107 @@ import redis.clients.util.SafeEncoder;
public class JedisTest extends JedisCommandTestBase {
@Test
public void useWithoutConnecting() {
Jedis jedis = new Jedis("localhost");
jedis.auth("foobared");
jedis.dbSize();
Jedis jedis = new Jedis("localhost");
jedis.auth("foobared");
jedis.dbSize();
}
@Test
public void checkBinaryData() {
byte[] bigdata = new byte[1777];
for (int b = 0; b < bigdata.length; b++) {
bigdata[b] = (byte) ((byte) b % 255);
}
Map<String, String> hash = new HashMap<String, String>();
hash.put("data", SafeEncoder.encode(bigdata));
byte[] bigdata = new byte[1777];
for (int b = 0; b < bigdata.length; b++) {
bigdata[b] = (byte) ((byte) b % 255);
}
Map<String, String> hash = new HashMap<String, String>();
hash.put("data", SafeEncoder.encode(bigdata));
String status = jedis.hmset("foo", hash);
assertEquals("OK", status);
assertEquals(hash, jedis.hgetAll("foo"));
String status = jedis.hmset("foo", hash);
assertEquals("OK", status);
assertEquals(hash, jedis.hgetAll("foo"));
}
@Test
public void connectWithShardInfo() {
JedisShardInfo shardInfo = new JedisShardInfo("localhost",
Protocol.DEFAULT_PORT);
shardInfo.setPassword("foobared");
Jedis jedis = new Jedis(shardInfo);
jedis.get("foo");
JedisShardInfo shardInfo = new JedisShardInfo("localhost",
Protocol.DEFAULT_PORT);
shardInfo.setPassword("foobared");
Jedis jedis = new Jedis(shardInfo);
jedis.get("foo");
}
@Test(expected = JedisConnectionException.class)
public void timeoutConnection() throws Exception {
jedis = new Jedis("localhost", 6379, 15000);
jedis.auth("foobared");
jedis.configSet("timeout", "1");
Thread.sleep(2000);
jedis.hmget("foobar", "foo");
jedis = new Jedis("localhost", 6379, 15000);
jedis.auth("foobared");
jedis.configSet("timeout", "1");
Thread.sleep(2000);
jedis.hmget("foobar", "foo");
}
@Test(expected = JedisConnectionException.class)
public void timeoutConnectionWithURI() throws Exception {
jedis = new Jedis(new URI("redis://:foobared@localhost:6380/2"), 15000);
jedis.configSet("timeout", "1");
Thread.sleep(2000);
jedis.hmget("foobar", "foo");
jedis = new Jedis(new URI("redis://:foobared@localhost:6380/2"), 15000);
jedis.configSet("timeout", "1");
Thread.sleep(2000);
jedis.hmget("foobar", "foo");
}
@Test(expected = JedisDataException.class)
public void failWhenSendingNullValues() {
jedis.set("foo", null);
jedis.set("foo", null);
}
@Test
public void shouldReconnectToSameDB() throws IOException {
jedis.select(1);
jedis.set("foo", "bar");
jedis.getClient().getSocket().shutdownInput();
jedis.getClient().getSocket().shutdownOutput();
assertEquals("bar", jedis.get("foo"));
jedis.select(1);
jedis.set("foo", "bar");
jedis.getClient().getSocket().shutdownInput();
jedis.getClient().getSocket().shutdownOutput();
assertEquals("bar", jedis.get("foo"));
}
@Test
public void startWithUrlString() {
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
Jedis jedis = new Jedis("redis://:foobared@localhost:6380/2");
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
Jedis jedis = new Jedis("redis://:foobared@localhost:6380/2");
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
}
@Test
public void startWithUrl() throws URISyntaxException {
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
Jedis jedis = new Jedis(new URI("redis://:foobared@localhost:6380/2"));
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
Jedis jedis = new Jedis(new URI("redis://:foobared@localhost:6380/2"));
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
}
@Test
public void allowUrlWithNoDBAndNoPassword() {
Jedis jedis = new Jedis("redis://localhost:6380");
jedis.auth("foobared");
assertEquals(jedis.getClient().getHost(), "localhost");
assertEquals(jedis.getClient().getPort(), 6380);
assertEquals(jedis.getDB(), (Long) 0L);
Jedis jedis = new Jedis("redis://localhost:6380");
jedis.auth("foobared");
assertEquals(jedis.getClient().getHost(), "localhost");
assertEquals(jedis.getClient().getPort(), 6380);
assertEquals(jedis.getDB(), (Long) 0L);
jedis = new Jedis("redis://localhost:6380/");
jedis.auth("foobared");
assertEquals(jedis.getClient().getHost(), "localhost");
assertEquals(jedis.getClient().getPort(), 6380);
assertEquals(jedis.getDB(), (Long) 0L);
jedis = new Jedis("redis://localhost:6380/");
jedis.auth("foobared");
assertEquals(jedis.getClient().getHost(), "localhost");
assertEquals(jedis.getClient().getPort(), 6380);
assertEquals(jedis.getDB(), (Long) 0L);
}
@Test
public void checkCloseable() {
jedis.close();
BinaryJedis bj = new BinaryJedis("localhost");
bj.connect();
bj.close();
jedis.close();
BinaryJedis bj = new BinaryJedis("localhost");
bj.connect();
bj.close();
}
}

View File

@@ -8,18 +8,18 @@ import org.junit.Assert;
public abstract class JedisTestBase extends Assert {
protected void assertEquals(List<byte[]> expected, List<byte[]> actual) {
assertEquals(expected.size(), actual.size());
for (int n = 0; n < expected.size(); n++) {
assertArrayEquals(expected.get(n), actual.get(n));
}
assertEquals(expected.size(), actual.size());
for (int n = 0; n < expected.size(); n++) {
assertArrayEquals(expected.get(n), actual.get(n));
}
}
protected void assertEquals(Set<byte[]> expected, Set<byte[]> actual) {
assertEquals(expected.size(), actual.size());
Iterator<byte[]> iterator = expected.iterator();
Iterator<byte[]> iterator2 = actual.iterator();
while (iterator.hasNext() || iterator2.hasNext()) {
assertArrayEquals(iterator.next(), iterator2.next());
}
assertEquals(expected.size(), actual.size());
Iterator<byte[]> iterator = expected.iterator();
Iterator<byte[]> iterator2 = actual.iterator();
while (iterator.hasNext() || iterator2.hasNext()) {
assertArrayEquals(iterator.next(), iterator2.next());
}
}
}

View File

@@ -27,453 +27,453 @@ public class PipeliningTest extends Assert {
@Before
public void setUp() throws Exception {
jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500);
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500);
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
}
@Test
public void pipeline() throws UnsupportedEncodingException {
Pipeline p = jedis.pipelined();
p.set("foo", "bar");
p.get("foo");
List<Object> results = p.syncAndReturnAll();
Pipeline p = jedis.pipelined();
p.set("foo", "bar");
p.get("foo");
List<Object> results = p.syncAndReturnAll();
assertEquals(2, results.size());
assertEquals("OK", results.get(0));
assertEquals("bar", results.get(1));
assertEquals(2, results.size());
assertEquals("OK", results.get(0));
assertEquals("bar", results.get(1));
}
@Test
public void pipelineResponse() {
jedis.set("string", "foo");
jedis.lpush("list", "foo");
jedis.hset("hash", "foo", "bar");
jedis.zadd("zset", 1, "foo");
jedis.sadd("set", "foo");
jedis.setrange("setrange", 0, "0123456789");
byte[] bytesForSetRange = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
jedis.setrange("setrangebytes".getBytes(), 0, bytesForSetRange);
jedis.set("string", "foo");
jedis.lpush("list", "foo");
jedis.hset("hash", "foo", "bar");
jedis.zadd("zset", 1, "foo");
jedis.sadd("set", "foo");
jedis.setrange("setrange", 0, "0123456789");
byte[] bytesForSetRange = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
jedis.setrange("setrangebytes".getBytes(), 0, bytesForSetRange);
Pipeline p = jedis.pipelined();
Response<String> string = p.get("string");
Response<String> list = p.lpop("list");
Response<String> hash = p.hget("hash", "foo");
Response<Set<String>> zset = p.zrange("zset", 0, -1);
Response<String> set = p.spop("set");
Response<Boolean> blist = p.exists("list");
Response<Double> zincrby = p.zincrby("zset", 1, "foo");
Response<Long> zcard = p.zcard("zset");
p.lpush("list", "bar");
Response<List<String>> lrange = p.lrange("list", 0, -1);
Response<Map<String, String>> hgetAll = p.hgetAll("hash");
p.sadd("set", "foo");
Response<Set<String>> smembers = p.smembers("set");
Response<Set<Tuple>> zrangeWithScores = p.zrangeWithScores("zset", 0,
-1);
Response<String> getrange = p.getrange("setrange", 1, 3);
Response<byte[]> getrangeBytes = p.getrange("setrangebytes".getBytes(),
6, 8);
p.sync();
Pipeline p = jedis.pipelined();
Response<String> string = p.get("string");
Response<String> list = p.lpop("list");
Response<String> hash = p.hget("hash", "foo");
Response<Set<String>> zset = p.zrange("zset", 0, -1);
Response<String> set = p.spop("set");
Response<Boolean> blist = p.exists("list");
Response<Double> zincrby = p.zincrby("zset", 1, "foo");
Response<Long> zcard = p.zcard("zset");
p.lpush("list", "bar");
Response<List<String>> lrange = p.lrange("list", 0, -1);
Response<Map<String, String>> hgetAll = p.hgetAll("hash");
p.sadd("set", "foo");
Response<Set<String>> smembers = p.smembers("set");
Response<Set<Tuple>> zrangeWithScores = p.zrangeWithScores("zset", 0,
-1);
Response<String> getrange = p.getrange("setrange", 1, 3);
Response<byte[]> getrangeBytes = p.getrange("setrangebytes".getBytes(),
6, 8);
p.sync();
assertEquals("foo", string.get());
assertEquals("foo", list.get());
assertEquals("bar", hash.get());
assertEquals("foo", zset.get().iterator().next());
assertEquals("foo", set.get());
assertEquals(false, blist.get());
assertEquals(Double.valueOf(2), zincrby.get());
assertEquals(Long.valueOf(1), zcard.get());
assertEquals(1, lrange.get().size());
assertNotNull(hgetAll.get().get("foo"));
assertEquals(1, smembers.get().size());
assertEquals(1, zrangeWithScores.get().size());
assertEquals("123", getrange.get());
byte[] expectedGetRangeBytes = { 6, 7, 8 };
assertArrayEquals(expectedGetRangeBytes, getrangeBytes.get());
assertEquals("foo", string.get());
assertEquals("foo", list.get());
assertEquals("bar", hash.get());
assertEquals("foo", zset.get().iterator().next());
assertEquals("foo", set.get());
assertEquals(false, blist.get());
assertEquals(Double.valueOf(2), zincrby.get());
assertEquals(Long.valueOf(1), zcard.get());
assertEquals(1, lrange.get().size());
assertNotNull(hgetAll.get().get("foo"));
assertEquals(1, smembers.get().size());
assertEquals(1, zrangeWithScores.get().size());
assertEquals("123", getrange.get());
byte[] expectedGetRangeBytes = { 6, 7, 8 };
assertArrayEquals(expectedGetRangeBytes, getrangeBytes.get());
}
@Test
public void pipelineResponseWithData() {
jedis.zadd("zset", 1, "foo");
jedis.zadd("zset", 1, "foo");
Pipeline p = jedis.pipelined();
Response<Double> score = p.zscore("zset", "foo");
p.sync();
Pipeline p = jedis.pipelined();
Response<Double> score = p.zscore("zset", "foo");
p.sync();
assertNotNull(score.get());
assertNotNull(score.get());
}
@Test
public void pipelineBinarySafeHashCommands() {
jedis.hset("key".getBytes(), "f1".getBytes(), "v111".getBytes());
jedis.hset("key".getBytes(), "f22".getBytes(), "v2222".getBytes());
jedis.hset("key".getBytes(), "f1".getBytes(), "v111".getBytes());
jedis.hset("key".getBytes(), "f22".getBytes(), "v2222".getBytes());
Pipeline p = jedis.pipelined();
Response<Map<byte[], byte[]>> fmap = p.hgetAll("key".getBytes());
Response<Set<byte[]>> fkeys = p.hkeys("key".getBytes());
Response<List<byte[]>> fordered = p.hmget("key".getBytes(),
"f22".getBytes(), "f1".getBytes());
Response<List<byte[]>> fvals = p.hvals("key".getBytes());
p.sync();
Pipeline p = jedis.pipelined();
Response<Map<byte[], byte[]>> fmap = p.hgetAll("key".getBytes());
Response<Set<byte[]>> fkeys = p.hkeys("key".getBytes());
Response<List<byte[]>> fordered = p.hmget("key".getBytes(),
"f22".getBytes(), "f1".getBytes());
Response<List<byte[]>> fvals = p.hvals("key".getBytes());
p.sync();
assertNotNull(fmap.get());
// we have to do these strange contortions because byte[] is not a very
// good key
// for a java Map. It only works with equality (you need the exact key
// object to retrieve
// the value) I recommend we switch to using ByteBuffer or something
// similar:
// http://stackoverflow.com/questions/1058149/using-a-byte-array-as-hashmap-key-java
Map<byte[], byte[]> map = fmap.get();
Set<byte[]> mapKeys = map.keySet();
Iterator<byte[]> iterMap = mapKeys.iterator();
byte[] firstMapKey = iterMap.next();
byte[] secondMapKey = iterMap.next();
assertFalse(iterMap.hasNext());
verifyHasBothValues(firstMapKey, secondMapKey, "f1".getBytes(),
"f22".getBytes());
byte[] firstMapValue = map.get(firstMapKey);
byte[] secondMapValue = map.get(secondMapKey);
verifyHasBothValues(firstMapValue, secondMapValue, "v111".getBytes(),
"v2222".getBytes());
assertNotNull(fmap.get());
// we have to do these strange contortions because byte[] is not a very
// good key
// for a java Map. It only works with equality (you need the exact key
// object to retrieve
// the value) I recommend we switch to using ByteBuffer or something
// similar:
// http://stackoverflow.com/questions/1058149/using-a-byte-array-as-hashmap-key-java
Map<byte[], byte[]> map = fmap.get();
Set<byte[]> mapKeys = map.keySet();
Iterator<byte[]> iterMap = mapKeys.iterator();
byte[] firstMapKey = iterMap.next();
byte[] secondMapKey = iterMap.next();
assertFalse(iterMap.hasNext());
verifyHasBothValues(firstMapKey, secondMapKey, "f1".getBytes(),
"f22".getBytes());
byte[] firstMapValue = map.get(firstMapKey);
byte[] secondMapValue = map.get(secondMapKey);
verifyHasBothValues(firstMapValue, secondMapValue, "v111".getBytes(),
"v2222".getBytes());
assertNotNull(fkeys.get());
Iterator<byte[]> iter = fkeys.get().iterator();
byte[] firstKey = iter.next();
byte[] secondKey = iter.next();
assertFalse(iter.hasNext());
verifyHasBothValues(firstKey, secondKey, "f1".getBytes(),
"f22".getBytes());
assertNotNull(fkeys.get());
Iterator<byte[]> iter = fkeys.get().iterator();
byte[] firstKey = iter.next();
byte[] secondKey = iter.next();
assertFalse(iter.hasNext());
verifyHasBothValues(firstKey, secondKey, "f1".getBytes(),
"f22".getBytes());
assertNotNull(fordered.get());
assertArrayEquals("v2222".getBytes(), fordered.get().get(0));
assertArrayEquals("v111".getBytes(), fordered.get().get(1));
assertNotNull(fordered.get());
assertArrayEquals("v2222".getBytes(), fordered.get().get(0));
assertArrayEquals("v111".getBytes(), fordered.get().get(1));
assertNotNull(fvals.get());
assertEquals(2, fvals.get().size());
byte[] firstValue = fvals.get().get(0);
byte[] secondValue = fvals.get().get(1);
verifyHasBothValues(firstValue, secondValue, "v111".getBytes(),
"v2222".getBytes());
assertNotNull(fvals.get());
assertEquals(2, fvals.get().size());
byte[] firstValue = fvals.get().get(0);
byte[] secondValue = fvals.get().get(1);
verifyHasBothValues(firstValue, secondValue, "v111".getBytes(),
"v2222".getBytes());
}
private void verifyHasBothValues(byte[] firstKey, byte[] secondKey,
byte[] value1, byte[] value2) {
assertFalse(Arrays.equals(firstKey, secondKey));
assertTrue(Arrays.equals(firstKey, value1)
|| Arrays.equals(firstKey, value2));
assertTrue(Arrays.equals(secondKey, value1)
|| Arrays.equals(secondKey, value2));
byte[] value1, byte[] value2) {
assertFalse(Arrays.equals(firstKey, secondKey));
assertTrue(Arrays.equals(firstKey, value1)
|| Arrays.equals(firstKey, value2));
assertTrue(Arrays.equals(secondKey, value1)
|| Arrays.equals(secondKey, value2));
}
@Test
public void pipelineSelect() {
Pipeline p = jedis.pipelined();
p.select(1);
p.sync();
Pipeline p = jedis.pipelined();
p.select(1);
p.sync();
}
@Test
public void pipelineResponseWithoutData() {
jedis.zadd("zset", 1, "foo");
jedis.zadd("zset", 1, "foo");
Pipeline p = jedis.pipelined();
Response<Double> score = p.zscore("zset", "bar");
p.sync();
Pipeline p = jedis.pipelined();
Response<Double> score = p.zscore("zset", "bar");
p.sync();
assertNull(score.get());
assertNull(score.get());
}
@Test(expected = JedisDataException.class)
public void pipelineResponseWithinPipeline() {
jedis.set("string", "foo");
jedis.set("string", "foo");
Pipeline p = jedis.pipelined();
Response<String> string = p.get("string");
string.get();
p.sync();
Pipeline p = jedis.pipelined();
Response<String> string = p.get("string");
string.get();
p.sync();
}
@Test
public void pipelineWithPubSub() {
Pipeline pipelined = jedis.pipelined();
Response<Long> p1 = pipelined.publish("foo", "bar");
Response<Long> p2 = pipelined.publish("foo".getBytes(),
"bar".getBytes());
pipelined.sync();
assertEquals(0, p1.get().longValue());
assertEquals(0, p2.get().longValue());
Pipeline pipelined = jedis.pipelined();
Response<Long> p1 = pipelined.publish("foo", "bar");
Response<Long> p2 = pipelined.publish("foo".getBytes(),
"bar".getBytes());
pipelined.sync();
assertEquals(0, p1.get().longValue());
assertEquals(0, p2.get().longValue());
}
@Test
public void canRetrieveUnsetKey() {
Pipeline p = jedis.pipelined();
Response<String> shouldNotExist = p.get(UUID.randomUUID().toString());
p.sync();
assertNull(shouldNotExist.get());
Pipeline p = jedis.pipelined();
Response<String> shouldNotExist = p.get(UUID.randomUUID().toString());
p.sync();
assertNull(shouldNotExist.get());
}
@Test
public void piplineWithError() {
Pipeline p = jedis.pipelined();
p.set("foo", "bar");
Response<Set<String>> error = p.smembers("foo");
Response<String> r = p.get("foo");
p.sync();
try {
error.get();
fail();
} catch (JedisDataException e) {
// that is fine we should be here
}
assertEquals(r.get(), "bar");
Pipeline p = jedis.pipelined();
p.set("foo", "bar");
Response<Set<String>> error = p.smembers("foo");
Response<String> r = p.get("foo");
p.sync();
try {
error.get();
fail();
} catch (JedisDataException e) {
// that is fine we should be here
}
assertEquals(r.get(), "bar");
}
@Test
public void multi() {
Pipeline p = jedis.pipelined();
p.multi();
Response<Long> r1 = p.hincrBy("a", "f1", -1);
Response<Long> r2 = p.hincrBy("a", "f1", -2);
Response<List<Object>> r3 = p.exec();
List<Object> result = p.syncAndReturnAll();
Pipeline p = jedis.pipelined();
p.multi();
Response<Long> r1 = p.hincrBy("a", "f1", -1);
Response<Long> r2 = p.hincrBy("a", "f1", -2);
Response<List<Object>> r3 = p.exec();
List<Object> result = p.syncAndReturnAll();
assertEquals(new Long(-1), r1.get());
assertEquals(new Long(-3), r2.get());
assertEquals(new Long(-1), r1.get());
assertEquals(new Long(-3), r2.get());
assertEquals(4, result.size());
assertEquals(4, result.size());
assertEquals("OK", result.get(0));
assertEquals("QUEUED", result.get(1));
assertEquals("QUEUED", result.get(2));
assertEquals("OK", result.get(0));
assertEquals("QUEUED", result.get(1));
assertEquals("QUEUED", result.get(2));
// 4th result is a list with the results from the multi
@SuppressWarnings("unchecked")
List<Object> multiResult = (List<Object>) result.get(3);
assertEquals(new Long(-1), multiResult.get(0));
assertEquals(new Long(-3), multiResult.get(1));
// 4th result is a list with the results from the multi
@SuppressWarnings("unchecked")
List<Object> multiResult = (List<Object>) result.get(3);
assertEquals(new Long(-1), multiResult.get(0));
assertEquals(new Long(-3), multiResult.get(1));
assertEquals(new Long(-1), r3.get().get(0));
assertEquals(new Long(-3), r3.get().get(1));
assertEquals(new Long(-1), r3.get().get(0));
assertEquals(new Long(-3), r3.get().get(1));
}
@Test
public void multiWithSync() {
jedis.set("foo", "314");
jedis.set("bar", "foo");
jedis.set("hello", "world");
Pipeline p = jedis.pipelined();
Response<String> r1 = p.get("bar");
p.multi();
Response<String> r2 = p.get("foo");
p.exec();
Response<String> r3 = p.get("hello");
p.sync();
jedis.set("foo", "314");
jedis.set("bar", "foo");
jedis.set("hello", "world");
Pipeline p = jedis.pipelined();
Response<String> r1 = p.get("bar");
p.multi();
Response<String> r2 = p.get("foo");
p.exec();
Response<String> r3 = p.get("hello");
p.sync();
// before multi
assertEquals("foo", r1.get());
// It should be readable whether exec's response was built or not
assertEquals("314", r2.get());
// after multi
assertEquals("world", r3.get());
// before multi
assertEquals("foo", r1.get());
// It should be readable whether exec's response was built or not
assertEquals("314", r2.get());
// after multi
assertEquals("world", r3.get());
}
@Test(expected = JedisDataException.class)
public void pipelineExecShoudThrowJedisDataExceptionWhenNotInMulti() {
Pipeline pipeline = jedis.pipelined();
pipeline.exec();
Pipeline pipeline = jedis.pipelined();
pipeline.exec();
}
@Test(expected = JedisDataException.class)
public void pipelineDiscardShoudThrowJedisDataExceptionWhenNotInMulti() {
Pipeline pipeline = jedis.pipelined();
pipeline.discard();
Pipeline pipeline = jedis.pipelined();
pipeline.discard();
}
@Test(expected = JedisDataException.class)
public void pipelineMultiShoudThrowJedisDataExceptionWhenAlreadyInMulti() {
Pipeline pipeline = jedis.pipelined();
pipeline.multi();
pipeline.set("foo", "3");
pipeline.multi();
Pipeline pipeline = jedis.pipelined();
pipeline.multi();
pipeline.set("foo", "3");
pipeline.multi();
}
@Test
public void testDiscardInPipeline() {
Pipeline pipeline = jedis.pipelined();
pipeline.multi();
pipeline.set("foo", "bar");
Response<String> discard = pipeline.discard();
Response<String> get = pipeline.get("foo");
pipeline.sync();
discard.get();
get.get();
Pipeline pipeline = jedis.pipelined();
pipeline.multi();
pipeline.set("foo", "bar");
Response<String> discard = pipeline.discard();
Response<String> get = pipeline.get("foo");
pipeline.sync();
discard.get();
get.get();
}
@Test
public void testEval() {
String script = "return 'success!'";
String script = "return 'success!'";
Pipeline p = jedis.pipelined();
Response<String> result = p.eval(script);
p.sync();
Pipeline p = jedis.pipelined();
Response<String> result = p.eval(script);
p.sync();
assertEquals("success!", result.get());
assertEquals("success!", result.get());
}
@Test
public void testEvalKeyAndArg() {
String key = "test";
String arg = "3";
String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])";
String key = "test";
String arg = "3";
String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])";
Pipeline p = jedis.pipelined();
p.set(key, "0");
Response<String> result0 = p.eval(script, Arrays.asList(key),
Arrays.asList(arg));
p.incr(key);
Response<String> result1 = p.eval(script, Arrays.asList(key),
Arrays.asList(arg));
Response<String> result2 = p.get(key);
p.sync();
Pipeline p = jedis.pipelined();
p.set(key, "0");
Response<String> result0 = p.eval(script, Arrays.asList(key),
Arrays.asList(arg));
p.incr(key);
Response<String> result1 = p.eval(script, Arrays.asList(key),
Arrays.asList(arg));
Response<String> result2 = p.get(key);
p.sync();
assertNull(result0.get());
assertNull(result1.get());
assertEquals("13", result2.get());
assertNull(result0.get());
assertNull(result1.get());
assertEquals("13", result2.get());
}
@Test
public void testEvalsha() {
String script = "return 'success!'";
String sha1 = jedis.scriptLoad(script);
String script = "return 'success!'";
String sha1 = jedis.scriptLoad(script);
assertTrue(jedis.scriptExists(sha1));
assertTrue(jedis.scriptExists(sha1));
Pipeline p = jedis.pipelined();
Response<String> result = p.evalsha(sha1);
p.sync();
Pipeline p = jedis.pipelined();
Response<String> result = p.evalsha(sha1);
p.sync();
assertEquals("success!", result.get());
assertEquals("success!", result.get());
}
@Test
public void testEvalshaKeyAndArg() {
String key = "test";
String arg = "3";
String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])";
String sha1 = jedis.scriptLoad(script);
String key = "test";
String arg = "3";
String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])";
String sha1 = jedis.scriptLoad(script);
assertTrue(jedis.scriptExists(sha1));
assertTrue(jedis.scriptExists(sha1));
Pipeline p = jedis.pipelined();
p.set(key, "0");
Response<String> result0 = p.evalsha(sha1, Arrays.asList(key),
Arrays.asList(arg));
p.incr(key);
Response<String> result1 = p.evalsha(sha1, Arrays.asList(key),
Arrays.asList(arg));
Response<String> result2 = p.get(key);
p.sync();
Pipeline p = jedis.pipelined();
p.set(key, "0");
Response<String> result0 = p.evalsha(sha1, Arrays.asList(key),
Arrays.asList(arg));
p.incr(key);
Response<String> result1 = p.evalsha(sha1, Arrays.asList(key),
Arrays.asList(arg));
Response<String> result2 = p.get(key);
p.sync();
assertNull(result0.get());
assertNull(result1.get());
assertEquals("13", result2.get());
assertNull(result0.get());
assertNull(result1.get());
assertEquals("13", result2.get());
}
@Test
public void testPipelinedTransactionResponse() {
String key1 = "key1";
String val1 = "val1";
String key1 = "key1";
String val1 = "val1";
String key2 = "key2";
String val2 = "val2";
String key2 = "key2";
String val2 = "val2";
String key3 = "key3";
String field1 = "field1";
String field2 = "field2";
String field3 = "field3";
String field4 = "field4";
String key3 = "key3";
String field1 = "field1";
String field2 = "field2";
String field3 = "field3";
String field4 = "field4";
String value1 = "value1";
String value2 = "value2";
String value3 = "value3";
String value4 = "value4";
String value1 = "value1";
String value2 = "value2";
String value3 = "value3";
String value4 = "value4";
Map<String, String> hashMap = new HashMap<String, String>();
hashMap.put(field1, value1);
hashMap.put(field2, value2);
Map<String, String> hashMap = new HashMap<String, String>();
hashMap.put(field1, value1);
hashMap.put(field2, value2);
String key4 = "key4";
Map<String, String> hashMap1 = new HashMap<String, String>();
hashMap1.put(field3, value3);
hashMap1.put(field4, value4);
String key4 = "key4";
Map<String, String> hashMap1 = new HashMap<String, String>();
hashMap1.put(field3, value3);
hashMap1.put(field4, value4);
jedis.set(key1, val1);
jedis.set(key2, val2);
jedis.hmset(key3, hashMap);
jedis.hmset(key4, hashMap1);
jedis.set(key1, val1);
jedis.set(key2, val2);
jedis.hmset(key3, hashMap);
jedis.hmset(key4, hashMap1);
Pipeline pipeline = jedis.pipelined();
pipeline.multi();
Pipeline pipeline = jedis.pipelined();
pipeline.multi();
pipeline.get(key1);
pipeline.hgetAll(key2);
pipeline.hgetAll(key3);
pipeline.get(key4);
pipeline.get(key1);
pipeline.hgetAll(key2);
pipeline.hgetAll(key3);
pipeline.get(key4);
Response<List<Object>> response = pipeline.exec();
pipeline.sync();
Response<List<Object>> response = pipeline.exec();
pipeline.sync();
List<Object> result = response.get();
List<Object> result = response.get();
assertEquals(4, result.size());
assertEquals(4, result.size());
assertEquals("val1", result.get(0));
assertEquals("val1", result.get(0));
assertTrue(result.get(1) instanceof JedisDataException);
assertTrue(result.get(1) instanceof JedisDataException);
Map<String, String> hashMapReceived = (Map<String, String>) result
.get(2);
Iterator<String> iterator = hashMapReceived.keySet().iterator();
String mapKey1 = iterator.next();
String mapKey2 = iterator.next();
assertFalse(iterator.hasNext());
verifyHasBothValues(mapKey1, mapKey2, field1, field2);
String mapValue1 = hashMapReceived.get(mapKey1);
String mapValue2 = hashMapReceived.get(mapKey2);
verifyHasBothValues(mapValue1, mapValue2, value1, value2);
Map<String, String> hashMapReceived = (Map<String, String>) result
.get(2);
Iterator<String> iterator = hashMapReceived.keySet().iterator();
String mapKey1 = iterator.next();
String mapKey2 = iterator.next();
assertFalse(iterator.hasNext());
verifyHasBothValues(mapKey1, mapKey2, field1, field2);
String mapValue1 = hashMapReceived.get(mapKey1);
String mapValue2 = hashMapReceived.get(mapKey2);
verifyHasBothValues(mapValue1, mapValue2, value1, value2);
assertTrue(result.get(3) instanceof JedisDataException);
assertTrue(result.get(3) instanceof JedisDataException);
}
@Test
public void testSyncWithNoCommandQueued() {
// we need to test with fresh instance of Jedis
Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500);
Pipeline pipeline = jedis2.pipelined();
pipeline.sync();
jedis2.close();
jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500);
pipeline = jedis2.pipelined();
List<Object> resp = pipeline.syncAndReturnAll();
assertTrue(resp.isEmpty());
jedis2.close();
// we need to test with fresh instance of Jedis
Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500);
Pipeline pipeline = jedis2.pipelined();
pipeline.sync();
jedis2.close();
jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500);
pipeline = jedis2.pipelined();
List<Object> resp = pipeline.syncAndReturnAll();
assertTrue(resp.isEmpty());
jedis2.close();
}
private void verifyHasBothValues(String firstKey, String secondKey,
String value1, String value2) {
assertFalse(firstKey.equals(secondKey));
assertTrue(firstKey.equals(value1) || firstKey.equals(value2));
assertTrue(secondKey.equals(value1) || secondKey.equals(value2));
String value1, String value2) {
assertFalse(firstKey.equals(secondKey));
assertTrue(firstKey.equals(value1) || firstKey.equals(value2));
assertTrue(secondKey.equals(value1) || secondKey.equals(value2));
}
}

View File

@@ -20,108 +20,108 @@ import redis.clients.util.SafeEncoder;
public class ProtocolTest extends JedisTestBase {
@Test
public void buildACommand() throws IOException {
PipedInputStream pis = new PipedInputStream();
BufferedInputStream bis = new BufferedInputStream(pis);
PipedOutputStream pos = new PipedOutputStream(pis);
RedisOutputStream ros = new RedisOutputStream(pos);
PipedInputStream pis = new PipedInputStream();
BufferedInputStream bis = new BufferedInputStream(pis);
PipedOutputStream pos = new PipedOutputStream(pis);
RedisOutputStream ros = new RedisOutputStream(pos);
Protocol.sendCommand(ros, Protocol.Command.GET,
"SOMEKEY".getBytes(Protocol.CHARSET));
ros.flush();
pos.close();
String expectedCommand = "*2\r\n$3\r\nGET\r\n$7\r\nSOMEKEY\r\n";
Protocol.sendCommand(ros, Protocol.Command.GET,
"SOMEKEY".getBytes(Protocol.CHARSET));
ros.flush();
pos.close();
String expectedCommand = "*2\r\n$3\r\nGET\r\n$7\r\nSOMEKEY\r\n";
int b;
StringBuilder sb = new StringBuilder();
while ((b = bis.read()) != -1) {
sb.append((char) b);
}
int b;
StringBuilder sb = new StringBuilder();
while ((b = bis.read()) != -1) {
sb.append((char) b);
}
assertEquals(expectedCommand, sb.toString());
assertEquals(expectedCommand, sb.toString());
}
@Test(expected = IOException.class)
public void writeOverflow() throws IOException {
RedisOutputStream ros = new RedisOutputStream(new OutputStream() {
RedisOutputStream ros = new RedisOutputStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
throw new IOException("thrown exception");
@Override
public void write(int b) throws IOException {
throw new IOException("thrown exception");
}
});
}
});
ros.write(new byte[8191]);
ros.write(new byte[8191]);
try {
ros.write((byte) '*');
} catch (IOException ioe) {
}
try {
ros.write((byte) '*');
} catch (IOException ioe) {
}
ros.write((byte) '*');
ros.write((byte) '*');
}
@Test
public void bulkReply() {
InputStream is = new ByteArrayInputStream("$6\r\nfoobar\r\n".getBytes());
byte[] response = (byte[]) Protocol.read(new RedisInputStream(is));
assertArrayEquals(SafeEncoder.encode("foobar"), response);
InputStream is = new ByteArrayInputStream("$6\r\nfoobar\r\n".getBytes());
byte[] response = (byte[]) Protocol.read(new RedisInputStream(is));
assertArrayEquals(SafeEncoder.encode("foobar"), response);
}
@Test
public void fragmentedBulkReply() {
FragmentedByteArrayInputStream fis = new FragmentedByteArrayInputStream(
"$30\r\n012345678901234567890123456789\r\n".getBytes());
byte[] response = (byte[]) Protocol.read(new RedisInputStream(fis));
assertArrayEquals(SafeEncoder.encode("012345678901234567890123456789"),
response);
FragmentedByteArrayInputStream fis = new FragmentedByteArrayInputStream(
"$30\r\n012345678901234567890123456789\r\n".getBytes());
byte[] response = (byte[]) Protocol.read(new RedisInputStream(fis));
assertArrayEquals(SafeEncoder.encode("012345678901234567890123456789"),
response);
}
@Test
public void nullBulkReply() {
InputStream is = new ByteArrayInputStream("$-1\r\n".getBytes());
String response = (String) Protocol.read(new RedisInputStream(is));
assertEquals(null, response);
InputStream is = new ByteArrayInputStream("$-1\r\n".getBytes());
String response = (String) Protocol.read(new RedisInputStream(is));
assertEquals(null, response);
}
@Test
public void singleLineReply() {
InputStream is = new ByteArrayInputStream("+OK\r\n".getBytes());
byte[] response = (byte[]) Protocol.read(new RedisInputStream(is));
assertArrayEquals(SafeEncoder.encode("OK"), response);
InputStream is = new ByteArrayInputStream("+OK\r\n".getBytes());
byte[] response = (byte[]) Protocol.read(new RedisInputStream(is));
assertArrayEquals(SafeEncoder.encode("OK"), response);
}
@Test
public void integerReply() {
InputStream is = new ByteArrayInputStream(":123\r\n".getBytes());
long response = (Long) Protocol.read(new RedisInputStream(is));
assertEquals(123, response);
InputStream is = new ByteArrayInputStream(":123\r\n".getBytes());
long response = (Long) Protocol.read(new RedisInputStream(is));
assertEquals(123, response);
}
@SuppressWarnings("unchecked")
@Test
public void multiBulkReply() {
InputStream is = new ByteArrayInputStream(
"*4\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$5\r\nHello\r\n$5\r\nWorld\r\n"
.getBytes());
List<byte[]> response = (List<byte[]>) Protocol
.read(new RedisInputStream(is));
List<byte[]> expected = new ArrayList<byte[]>();
expected.add(SafeEncoder.encode("foo"));
expected.add(SafeEncoder.encode("bar"));
expected.add(SafeEncoder.encode("Hello"));
expected.add(SafeEncoder.encode("World"));
InputStream is = new ByteArrayInputStream(
"*4\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$5\r\nHello\r\n$5\r\nWorld\r\n"
.getBytes());
List<byte[]> response = (List<byte[]>) Protocol
.read(new RedisInputStream(is));
List<byte[]> expected = new ArrayList<byte[]>();
expected.add(SafeEncoder.encode("foo"));
expected.add(SafeEncoder.encode("bar"));
expected.add(SafeEncoder.encode("Hello"));
expected.add(SafeEncoder.encode("World"));
assertEquals(expected, response);
assertEquals(expected, response);
}
@SuppressWarnings("unchecked")
@Test
public void nullMultiBulkReply() {
InputStream is = new ByteArrayInputStream("*-1\r\n".getBytes());
List<String> response = (List<String>) Protocol
.read(new RedisInputStream(is));
assertNull(response);
InputStream is = new ByteArrayInputStream("*-1\r\n".getBytes());
List<String> response = (List<String>) Protocol
.read(new RedisInputStream(is));
assertNull(response);
}
}

View File

@@ -29,135 +29,135 @@ import redis.clients.jedis.exceptions.JedisDataException;
public class ShardedJedisPipelineTest {
private static HostAndPort redis1 = HostAndPortUtil.getRedisServers()
.get(0);
.get(0);
private static HostAndPort redis2 = HostAndPortUtil.getRedisServers()
.get(1);
.get(1);
private ShardedJedis jedis;
@Before
public void setUp() throws Exception {
Jedis jedis = new Jedis(redis1.getHost(), redis1.getPort());
jedis.auth("foobared");
jedis.flushAll();
jedis.disconnect();
jedis = new Jedis(redis2.getHost(), redis2.getPort());
jedis.auth("foobared");
jedis.flushAll();
jedis.disconnect();
Jedis jedis = new Jedis(redis1.getHost(), redis1.getPort());
jedis.auth("foobared");
jedis.flushAll();
jedis.disconnect();
jedis = new Jedis(redis2.getHost(), redis2.getPort());
jedis.auth("foobared");
jedis.flushAll();
jedis.disconnect();
JedisShardInfo shardInfo1 = new JedisShardInfo(redis1.getHost(),
redis1.getPort());
JedisShardInfo shardInfo2 = new JedisShardInfo(redis2.getHost(),
redis2.getPort());
shardInfo1.setPassword("foobared");
shardInfo2.setPassword("foobared");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(shardInfo1);
shards.add(shardInfo2);
this.jedis = new ShardedJedis(shards);
JedisShardInfo shardInfo1 = new JedisShardInfo(redis1.getHost(),
redis1.getPort());
JedisShardInfo shardInfo2 = new JedisShardInfo(redis2.getHost(),
redis2.getPort());
shardInfo1.setPassword("foobared");
shardInfo2.setPassword("foobared");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(shardInfo1);
shards.add(shardInfo2);
this.jedis = new ShardedJedis(shards);
}
@Test
public void pipeline() throws UnsupportedEncodingException {
ShardedJedisPipeline p = jedis.pipelined();
p.set("foo", "bar");
p.get("foo");
List<Object> results = p.syncAndReturnAll();
ShardedJedisPipeline p = jedis.pipelined();
p.set("foo", "bar");
p.get("foo");
List<Object> results = p.syncAndReturnAll();
assertEquals(2, results.size());
assertEquals("OK", results.get(0));
assertEquals("bar", results.get(1));
assertEquals(2, results.size());
assertEquals("OK", results.get(0));
assertEquals("bar", results.get(1));
}
@Test
public void pipelineResponse() {
jedis.set("string", "foo");
jedis.lpush("list", "foo");
jedis.hset("hash", "foo", "bar");
jedis.zadd("zset", 1, "foo");
jedis.sadd("set", "foo");
jedis.set("string", "foo");
jedis.lpush("list", "foo");
jedis.hset("hash", "foo", "bar");
jedis.zadd("zset", 1, "foo");
jedis.sadd("set", "foo");
ShardedJedisPipeline p = jedis.pipelined();
Response<String> string = p.get("string");
Response<Long> del = p.del("string");
Response<String> emptyString = p.get("string");
Response<String> list = p.lpop("list");
Response<String> hash = p.hget("hash", "foo");
Response<Set<String>> zset = p.zrange("zset", 0, -1);
Response<String> set = p.spop("set");
Response<Boolean> blist = p.exists("list");
Response<Double> zincrby = p.zincrby("zset", 1, "foo");
Response<Long> zcard = p.zcard("zset");
p.lpush("list", "bar");
Response<List<String>> lrange = p.lrange("list", 0, -1);
Response<Map<String, String>> hgetAll = p.hgetAll("hash");
p.sadd("set", "foo");
Response<Set<String>> smembers = p.smembers("set");
Response<Set<Tuple>> zrangeWithScores = p.zrangeWithScores("zset", 0,
-1);
p.sync();
ShardedJedisPipeline p = jedis.pipelined();
Response<String> string = p.get("string");
Response<Long> del = p.del("string");
Response<String> emptyString = p.get("string");
Response<String> list = p.lpop("list");
Response<String> hash = p.hget("hash", "foo");
Response<Set<String>> zset = p.zrange("zset", 0, -1);
Response<String> set = p.spop("set");
Response<Boolean> blist = p.exists("list");
Response<Double> zincrby = p.zincrby("zset", 1, "foo");
Response<Long> zcard = p.zcard("zset");
p.lpush("list", "bar");
Response<List<String>> lrange = p.lrange("list", 0, -1);
Response<Map<String, String>> hgetAll = p.hgetAll("hash");
p.sadd("set", "foo");
Response<Set<String>> smembers = p.smembers("set");
Response<Set<Tuple>> zrangeWithScores = p.zrangeWithScores("zset", 0,
-1);
p.sync();
assertEquals("foo", string.get());
assertEquals(Long.valueOf(1), del.get());
assertNull(emptyString.get());
assertEquals("foo", list.get());
assertEquals("bar", hash.get());
assertEquals("foo", zset.get().iterator().next());
assertEquals("foo", set.get());
assertFalse(blist.get());
assertEquals(Double.valueOf(2), zincrby.get());
assertEquals(Long.valueOf(1), zcard.get());
assertEquals(1, lrange.get().size());
assertNotNull(hgetAll.get().get("foo"));
assertEquals(1, smembers.get().size());
assertEquals(1, zrangeWithScores.get().size());
assertEquals("foo", string.get());
assertEquals(Long.valueOf(1), del.get());
assertNull(emptyString.get());
assertEquals("foo", list.get());
assertEquals("bar", hash.get());
assertEquals("foo", zset.get().iterator().next());
assertEquals("foo", set.get());
assertFalse(blist.get());
assertEquals(Double.valueOf(2), zincrby.get());
assertEquals(Long.valueOf(1), zcard.get());
assertEquals(1, lrange.get().size());
assertNotNull(hgetAll.get().get("foo"));
assertEquals(1, smembers.get().size());
assertEquals(1, zrangeWithScores.get().size());
}
@Test(expected = JedisDataException.class)
public void pipelineResponseWithinPipeline() {
jedis.set("string", "foo");
jedis.set("string", "foo");
ShardedJedisPipeline p = jedis.pipelined();
Response<String> string = p.get("string");
string.get();
p.sync();
ShardedJedisPipeline p = jedis.pipelined();
Response<String> string = p.get("string");
string.get();
p.sync();
}
@Test
public void canRetrieveUnsetKey() {
ShardedJedisPipeline p = jedis.pipelined();
Response<String> shouldNotExist = p.get(UUID.randomUUID().toString());
p.sync();
assertNull(shouldNotExist.get());
ShardedJedisPipeline p = jedis.pipelined();
Response<String> shouldNotExist = p.get(UUID.randomUUID().toString());
p.sync();
assertNull(shouldNotExist.get());
}
@Test
public void testSyncWithNoCommandQueued() {
JedisShardInfo shardInfo1 = new JedisShardInfo(redis1.getHost(),
redis1.getPort());
JedisShardInfo shardInfo2 = new JedisShardInfo(redis2.getHost(),
redis2.getPort());
shardInfo1.setPassword("foobared");
shardInfo2.setPassword("foobared");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(shardInfo1);
shards.add(shardInfo2);
ShardedJedis jedis2 = new ShardedJedis(shards);
ShardedJedisPipeline pipeline = jedis2.pipelined();
pipeline.sync();
jedis2.close();
jedis2 = new ShardedJedis(shards);
pipeline = jedis2.pipelined();
List<Object> resp = pipeline.syncAndReturnAll();
assertTrue(resp.isEmpty());
jedis2.close();
JedisShardInfo shardInfo1 = new JedisShardInfo(redis1.getHost(),
redis1.getPort());
JedisShardInfo shardInfo2 = new JedisShardInfo(redis2.getHost(),
redis2.getPort());
shardInfo1.setPassword("foobared");
shardInfo2.setPassword("foobared");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(shardInfo1);
shards.add(shardInfo2);
ShardedJedis jedis2 = new ShardedJedis(shards);
ShardedJedisPipeline pipeline = jedis2.pipelined();
pipeline.sync();
jedis2.close();
jedis2 = new ShardedJedis(shards);
pipeline = jedis2.pipelined();
List<Object> resp = pipeline.syncAndReturnAll();
assertTrue(resp.isEmpty());
jedis2.close();
}
}

View File

@@ -20,295 +20,295 @@ import redis.clients.jedis.exceptions.JedisConnectionException;
public class ShardedJedisPoolTest extends Assert {
private static HostAndPort redis1 = HostAndPortUtil.getRedisServers()
.get(0);
.get(0);
private static HostAndPort redis2 = HostAndPortUtil.getRedisServers()
.get(1);
.get(1);
private List<JedisShardInfo> shards;
@Before
public void startUp() {
shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
shards.get(0).setPassword("foobared");
shards.get(1).setPassword("foobared");
Jedis j = new Jedis(shards.get(0));
j.connect();
j.flushAll();
j.disconnect();
j = new Jedis(shards.get(1));
j.connect();
j.flushAll();
j.disconnect();
shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
shards.get(0).setPassword("foobared");
shards.get(1).setPassword("foobared");
Jedis j = new Jedis(shards.get(0));
j.connect();
j.flushAll();
j.disconnect();
j = new Jedis(shards.get(1));
j.connect();
j.flushAll();
j.disconnect();
}
@Test
public void checkConnections() {
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.destroy();
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.destroy();
}
@Test
public void checkCloseableConnections() throws Exception {
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.close();
assertTrue(pool.isClosed());
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.close();
assertTrue(pool.isClosed());
}
@Test
public void checkConnectionWithDefaultPort() {
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.destroy();
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.destroy();
}
@Test
public void checkJedisIsReusedWhenReturned() {
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.set("foo", "0");
pool.returnResource(jedis);
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.set("foo", "0");
pool.returnResource(jedis);
jedis = pool.getResource();
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
jedis = pool.getResource();
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
}
@Test
public void checkPoolRepairedWhenJedisIsBroken() {
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.disconnect();
pool.returnBrokenResource(jedis);
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.disconnect();
pool.returnBrokenResource(jedis);
jedis = pool.getResource();
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
jedis = pool.getResource();
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
}
@Test(expected = JedisConnectionException.class)
public void checkPoolOverflow() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedis jedis = pool.getResource();
jedis.set("foo", "0");
ShardedJedis jedis = pool.getResource();
jedis.set("foo", "0");
ShardedJedis newJedis = pool.getResource();
newJedis.incr("foo");
ShardedJedis newJedis = pool.getResource();
newJedis.incr("foo");
}
@Test
public void shouldNotShareInstances() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(2);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(2);
ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedis j1 = pool.getResource();
ShardedJedis j2 = pool.getResource();
ShardedJedis j1 = pool.getResource();
ShardedJedis j2 = pool.getResource();
assertNotSame(j1.getShard("foo"), j2.getShard("foo"));
assertNotSame(j1.getShard("foo"), j2.getShard("foo"));
}
@Test
public void checkFailedJedisServer() {
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
}
@Test
public void shouldReturnActiveShardsWhenOneGoesOffline() {
GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
redisConfig.setTestOnBorrow(false);
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards);
ShardedJedis jedis = pool.getResource();
// fill the shards
for (int i = 0; i < 1000; i++) {
jedis.set("a-test-" + i, "0");
}
pool.returnResource(jedis);
// check quantity for each shard
Jedis j = new Jedis(shards.get(0));
j.connect();
Long c1 = j.dbSize();
j.disconnect();
j = new Jedis(shards.get(1));
j.connect();
Long c2 = j.dbSize();
j.disconnect();
// shutdown shard 2 and check thay the pool returns an instance with c1
// items on one shard
// alter shard 1 and recreate pool
pool.destroy();
shards.set(1, new JedisShardInfo("localhost", 1234));
pool = new ShardedJedisPool(redisConfig, shards);
jedis = pool.getResource();
Long actual = Long.valueOf(0);
Long fails = Long.valueOf(0);
for (int i = 0; i < 1000; i++) {
try {
jedis.get("a-test-" + i);
actual++;
} catch (RuntimeException e) {
fails++;
}
}
pool.returnResource(jedis);
pool.destroy();
assertEquals(actual, c1);
assertEquals(fails, c2);
GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
redisConfig.setTestOnBorrow(false);
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards);
ShardedJedis jedis = pool.getResource();
// fill the shards
for (int i = 0; i < 1000; i++) {
jedis.set("a-test-" + i, "0");
}
pool.returnResource(jedis);
// check quantity for each shard
Jedis j = new Jedis(shards.get(0));
j.connect();
Long c1 = j.dbSize();
j.disconnect();
j = new Jedis(shards.get(1));
j.connect();
Long c2 = j.dbSize();
j.disconnect();
// shutdown shard 2 and check thay the pool returns an instance with c1
// items on one shard
// alter shard 1 and recreate pool
pool.destroy();
shards.set(1, new JedisShardInfo("localhost", 1234));
pool = new ShardedJedisPool(redisConfig, shards);
jedis = pool.getResource();
Long actual = Long.valueOf(0);
Long fails = Long.valueOf(0);
for (int i = 0; i < 1000; i++) {
try {
jedis.get("a-test-" + i);
actual++;
} catch (RuntimeException e) {
fails++;
}
}
pool.returnResource(jedis);
pool.destroy();
assertEquals(actual, c1);
assertEquals(fails, c2);
}
@Test
public void startWithUrlString() {
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.set("foo", "bar");
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.set("foo", "bar");
j = new Jedis("localhost", 6379);
j.auth("foobared");
j.set("foo", "bar");
j = new Jedis("localhost", 6379);
j.auth("foobared");
j.set("foo", "bar");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo("redis://:foobared@localhost:6380"));
shards.add(new JedisShardInfo("redis://:foobared@localhost:6379"));
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo("redis://:foobared@localhost:6380"));
shards.add(new JedisShardInfo("redis://:foobared@localhost:6379"));
GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards);
GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards);
Jedis[] jedises = pool.getResource().getAllShards()
.toArray(new Jedis[2]);
Jedis[] jedises = pool.getResource().getAllShards()
.toArray(new Jedis[2]);
Jedis jedis = jedises[0];
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
Jedis jedis = jedises[0];
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
jedis = jedises[1];
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
jedis = jedises[1];
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
}
@Test
public void startWithUrl() throws URISyntaxException {
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.set("foo", "bar");
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.set("foo", "bar");
j = new Jedis("localhost", 6379);
j.auth("foobared");
j.set("foo", "bar");
j = new Jedis("localhost", 6379);
j.auth("foobared");
j.set("foo", "bar");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6380")));
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6379")));
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6380")));
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6379")));
GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards);
GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards);
Jedis[] jedises = pool.getResource().getAllShards()
.toArray(new Jedis[2]);
Jedis[] jedises = pool.getResource().getAllShards()
.toArray(new Jedis[2]);
Jedis jedis = jedises[0];
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
Jedis jedis = jedises[0];
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
jedis = jedises[1];
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
jedis = jedises[1];
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
}
@Test
public void returnResourceShouldResetState() throws URISyntaxException {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6380")));
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6379")));
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6380")));
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6379")));
ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedis jedis = pool.getResource();
jedis.set("pipelined", String.valueOf(0));
jedis.set("pipelined2", String.valueOf(0));
ShardedJedis jedis = pool.getResource();
jedis.set("pipelined", String.valueOf(0));
jedis.set("pipelined2", String.valueOf(0));
ShardedJedisPipeline pipeline = jedis.pipelined();
ShardedJedisPipeline pipeline = jedis.pipelined();
pipeline.incr("pipelined");
pipeline.incr("pipelined2");
pipeline.incr("pipelined");
pipeline.incr("pipelined2");
jedis.resetState();
jedis.resetState();
pipeline = jedis.pipelined();
pipeline.incr("pipelined");
pipeline.incr("pipelined2");
List<Object> results = pipeline.syncAndReturnAll();
pipeline = jedis.pipelined();
pipeline.incr("pipelined");
pipeline.incr("pipelined2");
List<Object> results = pipeline.syncAndReturnAll();
assertEquals(2, results.size());
pool.returnResource(jedis);
pool.destroy();
assertEquals(2, results.size());
pool.returnResource(jedis);
pool.destroy();
}
@Test
public void checkResourceIsCloseable() throws URISyntaxException {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6380")));
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6379")));
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6380")));
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6379")));
ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
} finally {
jedis.close();
}
ShardedJedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
} finally {
jedis.close();
}
ShardedJedis jedis2 = pool.getResource();
try {
assertEquals(jedis, jedis2);
} finally {
jedis2.close();
}
ShardedJedis jedis2 = pool.getResource();
try {
assertEquals(jedis, jedis2);
} finally {
jedis2.close();
}
}
}

View File

@@ -18,278 +18,278 @@ import redis.clients.util.Sharded;
public class ShardedJedisTest extends Assert {
private static HostAndPort redis1 = HostAndPortUtil.getRedisServers()
.get(0);
.get(0);
private static HostAndPort redis2 = HostAndPortUtil.getRedisServers()
.get(1);
.get(1);
private List<String> getKeysDifferentShard(ShardedJedis jedis) {
List<String> ret = new ArrayList<String>();
JedisShardInfo first = jedis.getShardInfo("a0");
ret.add("a0");
for (int i = 1; i < 100; ++i) {
JedisShardInfo actual = jedis.getShardInfo("a" + i);
if (actual != first) {
ret.add("a" + i);
break;
List<String> ret = new ArrayList<String>();
JedisShardInfo first = jedis.getShardInfo("a0");
ret.add("a0");
for (int i = 1; i < 100; ++i) {
JedisShardInfo actual = jedis.getShardInfo("a" + i);
if (actual != first) {
ret.add("a" + i);
break;
}
}
}
return ret;
}
return ret;
}
@Test
public void checkSharding() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
ShardedJedis jedis = new ShardedJedis(shards);
List<String> keys = getKeysDifferentShard(jedis);
JedisShardInfo s1 = jedis.getShardInfo(keys.get(0));
JedisShardInfo s2 = jedis.getShardInfo(keys.get(1));
assertNotSame(s1, s2);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
ShardedJedis jedis = new ShardedJedis(shards);
List<String> keys = getKeysDifferentShard(jedis);
JedisShardInfo s1 = jedis.getShardInfo(keys.get(0));
JedisShardInfo s2 = jedis.getShardInfo(keys.get(1));
assertNotSame(s1, s2);
}
@Test
public void trySharding() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo si = new JedisShardInfo(redis1.getHost(),
redis1.getPort());
si.setPassword("foobared");
shards.add(si);
si = new JedisShardInfo(redis2.getHost(), redis2.getPort());
si.setPassword("foobared");
shards.add(si);
ShardedJedis jedis = new ShardedJedis(shards);
jedis.set("a", "bar");
JedisShardInfo s1 = jedis.getShardInfo("a");
jedis.set("b", "bar1");
JedisShardInfo s2 = jedis.getShardInfo("b");
jedis.disconnect();
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo si = new JedisShardInfo(redis1.getHost(),
redis1.getPort());
si.setPassword("foobared");
shards.add(si);
si = new JedisShardInfo(redis2.getHost(), redis2.getPort());
si.setPassword("foobared");
shards.add(si);
ShardedJedis jedis = new ShardedJedis(shards);
jedis.set("a", "bar");
JedisShardInfo s1 = jedis.getShardInfo("a");
jedis.set("b", "bar1");
JedisShardInfo s2 = jedis.getShardInfo("b");
jedis.disconnect();
Jedis j = new Jedis(s1.getHost(), s1.getPort());
j.auth("foobared");
assertEquals("bar", j.get("a"));
j.disconnect();
Jedis j = new Jedis(s1.getHost(), s1.getPort());
j.auth("foobared");
assertEquals("bar", j.get("a"));
j.disconnect();
j = new Jedis(s2.getHost(), s2.getPort());
j.auth("foobared");
assertEquals("bar1", j.get("b"));
j.disconnect();
j = new Jedis(s2.getHost(), s2.getPort());
j.auth("foobared");
assertEquals("bar1", j.get("b"));
j.disconnect();
}
@Test
public void tryShardingWithMurmure() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo si = new JedisShardInfo(redis1.getHost(),
redis1.getPort());
si.setPassword("foobared");
shards.add(si);
si = new JedisShardInfo(redis2.getHost(), redis2.getPort());
si.setPassword("foobared");
shards.add(si);
ShardedJedis jedis = new ShardedJedis(shards, Hashing.MURMUR_HASH);
jedis.set("a", "bar");
JedisShardInfo s1 = jedis.getShardInfo("a");
jedis.set("b", "bar1");
JedisShardInfo s2 = jedis.getShardInfo("b");
jedis.disconnect();
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo si = new JedisShardInfo(redis1.getHost(),
redis1.getPort());
si.setPassword("foobared");
shards.add(si);
si = new JedisShardInfo(redis2.getHost(), redis2.getPort());
si.setPassword("foobared");
shards.add(si);
ShardedJedis jedis = new ShardedJedis(shards, Hashing.MURMUR_HASH);
jedis.set("a", "bar");
JedisShardInfo s1 = jedis.getShardInfo("a");
jedis.set("b", "bar1");
JedisShardInfo s2 = jedis.getShardInfo("b");
jedis.disconnect();
Jedis j = new Jedis(s1.getHost(), s1.getPort());
j.auth("foobared");
assertEquals("bar", j.get("a"));
j.disconnect();
Jedis j = new Jedis(s1.getHost(), s1.getPort());
j.auth("foobared");
assertEquals("bar", j.get("a"));
j.disconnect();
j = new Jedis(s2.getHost(), s2.getPort());
j.auth("foobared");
assertEquals("bar1", j.get("b"));
j.disconnect();
j = new Jedis(s2.getHost(), s2.getPort());
j.auth("foobared");
assertEquals("bar1", j.get("b"));
j.disconnect();
}
@Test
public void checkKeyTags() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
ShardedJedis jedis = new ShardedJedis(shards,
ShardedJedis.DEFAULT_KEY_TAG_PATTERN);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
ShardedJedis jedis = new ShardedJedis(shards,
ShardedJedis.DEFAULT_KEY_TAG_PATTERN);
assertEquals(jedis.getKeyTag("foo"), "foo");
assertEquals(jedis.getKeyTag("foo{bar}"), "bar");
assertEquals(jedis.getKeyTag("foo{bar}}"), "bar"); // default pattern is
// non greedy
assertEquals(jedis.getKeyTag("{bar}foo"), "bar"); // Key tag may appear
// anywhere
assertEquals(jedis.getKeyTag("f{bar}oo"), "bar"); // Key tag may appear
// anywhere
assertEquals(jedis.getKeyTag("foo"), "foo");
assertEquals(jedis.getKeyTag("foo{bar}"), "bar");
assertEquals(jedis.getKeyTag("foo{bar}}"), "bar"); // default pattern is
// non greedy
assertEquals(jedis.getKeyTag("{bar}foo"), "bar"); // Key tag may appear
// anywhere
assertEquals(jedis.getKeyTag("f{bar}oo"), "bar"); // Key tag may appear
// anywhere
JedisShardInfo s1 = jedis.getShardInfo("abc{bar}");
JedisShardInfo s2 = jedis.getShardInfo("foo{bar}");
assertSame(s1, s2);
JedisShardInfo s1 = jedis.getShardInfo("abc{bar}");
JedisShardInfo s2 = jedis.getShardInfo("foo{bar}");
assertSame(s1, s2);
List<String> keys = getKeysDifferentShard(jedis);
JedisShardInfo s3 = jedis.getShardInfo(keys.get(0));
JedisShardInfo s4 = jedis.getShardInfo(keys.get(1));
assertNotSame(s3, s4);
List<String> keys = getKeysDifferentShard(jedis);
JedisShardInfo s3 = jedis.getShardInfo(keys.get(0));
JedisShardInfo s4 = jedis.getShardInfo(keys.get(1));
assertNotSame(s3, s4);
ShardedJedis jedis2 = new ShardedJedis(shards);
ShardedJedis jedis2 = new ShardedJedis(shards);
assertEquals(jedis2.getKeyTag("foo"), "foo");
assertNotSame(jedis2.getKeyTag("foo{bar}"), "bar");
assertEquals(jedis2.getKeyTag("foo"), "foo");
assertNotSame(jedis2.getKeyTag("foo{bar}"), "bar");
JedisShardInfo s5 = jedis2.getShardInfo(keys.get(0) + "{bar}");
JedisShardInfo s6 = jedis2.getShardInfo(keys.get(1) + "{bar}");
assertNotSame(s5, s6);
JedisShardInfo s5 = jedis2.getShardInfo(keys.get(0) + "{bar}");
JedisShardInfo s6 = jedis2.getShardInfo(keys.get(1) + "{bar}");
assertNotSame(s5, s6);
}
@Test
public void testMD5Sharding() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3);
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2));
Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MD5);
int shard_6379 = 0;
int shard_6380 = 0;
int shard_6381 = 0;
for (int i = 0; i < 1000; i++) {
JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer
.toString(i));
switch (jedisShardInfo.getPort()) {
case 6379:
shard_6379++;
break;
case 6380:
shard_6380++;
break;
case 6381:
shard_6381++;
break;
default:
fail("Attempting to use a non-defined shard!!:"
+ jedisShardInfo);
break;
}
}
assertTrue(shard_6379 > 300 && shard_6379 < 400);
assertTrue(shard_6380 > 300 && shard_6380 < 400);
assertTrue(shard_6381 > 300 && shard_6381 < 400);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3);
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2));
Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MD5);
int shard_6379 = 0;
int shard_6380 = 0;
int shard_6381 = 0;
for (int i = 0; i < 1000; i++) {
JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer
.toString(i));
switch (jedisShardInfo.getPort()) {
case 6379:
shard_6379++;
break;
case 6380:
shard_6380++;
break;
case 6381:
shard_6381++;
break;
default:
fail("Attempting to use a non-defined shard!!:"
+ jedisShardInfo);
break;
}
}
assertTrue(shard_6379 > 300 && shard_6379 < 400);
assertTrue(shard_6380 > 300 && shard_6380 < 400);
assertTrue(shard_6381 > 300 && shard_6381 < 400);
}
@Test
public void testMurmurSharding() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3);
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2));
Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MURMUR_HASH);
int shard_6379 = 0;
int shard_6380 = 0;
int shard_6381 = 0;
for (int i = 0; i < 1000; i++) {
JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer
.toString(i));
switch (jedisShardInfo.getPort()) {
case 6379:
shard_6379++;
break;
case 6380:
shard_6380++;
break;
case 6381:
shard_6381++;
break;
default:
fail("Attempting to use a non-defined shard!!:"
+ jedisShardInfo);
break;
}
}
assertTrue(shard_6379 > 300 && shard_6379 < 400);
assertTrue(shard_6380 > 300 && shard_6380 < 400);
assertTrue(shard_6381 > 300 && shard_6381 < 400);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3);
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2));
Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MURMUR_HASH);
int shard_6379 = 0;
int shard_6380 = 0;
int shard_6381 = 0;
for (int i = 0; i < 1000; i++) {
JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer
.toString(i));
switch (jedisShardInfo.getPort()) {
case 6379:
shard_6379++;
break;
case 6380:
shard_6380++;
break;
case 6381:
shard_6381++;
break;
default:
fail("Attempting to use a non-defined shard!!:"
+ jedisShardInfo);
break;
}
}
assertTrue(shard_6379 > 300 && shard_6379 < 400);
assertTrue(shard_6380 > 300 && shard_6380 < 400);
assertTrue(shard_6381 > 300 && shard_6381 < 400);
}
@Test
public void testMasterSlaveShardingConsistency() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3);
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2));
Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MURMUR_HASH);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3);
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2));
Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MURMUR_HASH);
List<JedisShardInfo> otherShards = new ArrayList<JedisShardInfo>(3);
otherShards.add(new JedisShardInfo("otherhost", Protocol.DEFAULT_PORT));
otherShards.add(new JedisShardInfo("otherhost",
Protocol.DEFAULT_PORT + 1));
otherShards.add(new JedisShardInfo("otherhost",
Protocol.DEFAULT_PORT + 2));
Sharded<Jedis, JedisShardInfo> sharded2 = new Sharded<Jedis, JedisShardInfo>(
otherShards, Hashing.MURMUR_HASH);
List<JedisShardInfo> otherShards = new ArrayList<JedisShardInfo>(3);
otherShards.add(new JedisShardInfo("otherhost", Protocol.DEFAULT_PORT));
otherShards.add(new JedisShardInfo("otherhost",
Protocol.DEFAULT_PORT + 1));
otherShards.add(new JedisShardInfo("otherhost",
Protocol.DEFAULT_PORT + 2));
Sharded<Jedis, JedisShardInfo> sharded2 = new Sharded<Jedis, JedisShardInfo>(
otherShards, Hashing.MURMUR_HASH);
for (int i = 0; i < 1000; i++) {
JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer
.toString(i));
JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer
.toString(i));
assertEquals(shards.indexOf(jedisShardInfo),
otherShards.indexOf(jedisShardInfo2));
}
for (int i = 0; i < 1000; i++) {
JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer
.toString(i));
JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer
.toString(i));
assertEquals(shards.indexOf(jedisShardInfo),
otherShards.indexOf(jedisShardInfo2));
}
}
@Test
public void testMasterSlaveShardingConsistencyWithShardNaming() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3);
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT,
"HOST1:1234"));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1,
"HOST2:1234"));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2,
"HOST3:1234"));
Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MURMUR_HASH);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3);
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT,
"HOST1:1234"));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1,
"HOST2:1234"));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2,
"HOST3:1234"));
Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MURMUR_HASH);
List<JedisShardInfo> otherShards = new ArrayList<JedisShardInfo>(3);
otherShards.add(new JedisShardInfo("otherhost", Protocol.DEFAULT_PORT,
"HOST2:1234"));
otherShards.add(new JedisShardInfo("otherhost",
Protocol.DEFAULT_PORT + 1, "HOST3:1234"));
otherShards.add(new JedisShardInfo("otherhost",
Protocol.DEFAULT_PORT + 2, "HOST1:1234"));
Sharded<Jedis, JedisShardInfo> sharded2 = new Sharded<Jedis, JedisShardInfo>(
otherShards, Hashing.MURMUR_HASH);
List<JedisShardInfo> otherShards = new ArrayList<JedisShardInfo>(3);
otherShards.add(new JedisShardInfo("otherhost", Protocol.DEFAULT_PORT,
"HOST2:1234"));
otherShards.add(new JedisShardInfo("otherhost",
Protocol.DEFAULT_PORT + 1, "HOST3:1234"));
otherShards.add(new JedisShardInfo("otherhost",
Protocol.DEFAULT_PORT + 2, "HOST1:1234"));
Sharded<Jedis, JedisShardInfo> sharded2 = new Sharded<Jedis, JedisShardInfo>(
otherShards, Hashing.MURMUR_HASH);
for (int i = 0; i < 1000; i++) {
JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer
.toString(i));
JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer
.toString(i));
assertEquals(jedisShardInfo.getName(), jedisShardInfo2.getName());
}
for (int i = 0; i < 1000; i++) {
JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer
.toString(i));
JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer
.toString(i));
assertEquals(jedisShardInfo.getName(), jedisShardInfo2.getName());
}
}
@Test
public void checkCloseable() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
shards.get(0).setPassword("foobared");
shards.get(1).setPassword("foobared");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
shards.get(0).setPassword("foobared");
shards.get(1).setPassword("foobared");
ShardedJedis jedisShard = new ShardedJedis(shards);
try {
jedisShard.set("shard_closeable", "true");
} finally {
jedisShard.close();
}
ShardedJedis jedisShard = new ShardedJedis(shards);
try {
jedisShard.set("shard_closeable", "true");
} finally {
jedisShard.close();
}
for (Jedis jedis : jedisShard.getAllShards()) {
assertTrue(!jedis.isConnected());
}
for (Jedis jedis : jedisShard.getAllShards()) {
assertTrue(!jedis.isConnected());
}
}
}

View File

@@ -8,19 +8,19 @@ public class CRC16Benchmark {
private static final int TOTAL_OPERATIONS = 100000000;
private static String[] TEST_SET = { "", "123456789", "sfger132515",
"hae9Napahngaikeethievubaibogiech", "AAAAAAAAAAAAAAAAAAAAAA",
"Hello, World!" };
"hae9Napahngaikeethievubaibogiech", "AAAAAAAAAAAAAAAAAAAAAA",
"Hello, World!" };
public static void main(String[] args) {
long begin = Calendar.getInstance().getTimeInMillis();
long begin = Calendar.getInstance().getTimeInMillis();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
JedisClusterCRC16.getSlot(TEST_SET[n % TEST_SET.length]);
}
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
JedisClusterCRC16.getSlot(TEST_SET[n % TEST_SET.length]);
}
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " ops");
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " ops");
}
}

View File

@@ -13,24 +13,24 @@ public class GetSetBenchmark {
private static final int TOTAL_OPERATIONS = 100000;
public static void main(String[] args) throws UnknownHostException,
IOException {
Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort());
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
IOException {
Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort());
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
long begin = Calendar.getInstance().getTimeInMillis();
long begin = Calendar.getInstance().getTimeInMillis();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n;
jedis.set(key, "bar" + n);
jedis.get(key);
}
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n;
jedis.set(key, "bar" + n);
jedis.get(key);
}
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
jedis.disconnect();
jedis.disconnect();
System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
}
}

View File

@@ -19,33 +19,33 @@ public class HashingBenchmark {
private static final int TOTAL_OPERATIONS = 100000;
public static void main(String[] args) throws UnknownHostException,
IOException {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo shard = new JedisShardInfo(hnp1.getHost(),
hnp1.getPort());
shard.setPassword("foobared");
shards.add(shard);
shard = new JedisShardInfo(hnp2.getHost(), hnp2.getPort());
shard.setPassword("foobared");
shards.add(shard);
ShardedJedis jedis = new ShardedJedis(shards);
Collection<Jedis> allShards = jedis.getAllShards();
for (Jedis j : allShards) {
j.flushAll();
}
IOException {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo shard = new JedisShardInfo(hnp1.getHost(),
hnp1.getPort());
shard.setPassword("foobared");
shards.add(shard);
shard = new JedisShardInfo(hnp2.getHost(), hnp2.getPort());
shard.setPassword("foobared");
shards.add(shard);
ShardedJedis jedis = new ShardedJedis(shards);
Collection<Jedis> allShards = jedis.getAllShards();
for (Jedis j : allShards) {
j.flushAll();
}
long begin = Calendar.getInstance().getTimeInMillis();
long begin = Calendar.getInstance().getTimeInMillis();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n;
jedis.set(key, "bar" + n);
jedis.get(key);
}
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n;
jedis.set(key, "bar" + n);
jedis.get(key);
}
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
jedis.disconnect();
jedis.disconnect();
System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
}
}

View File

@@ -14,26 +14,26 @@ public class PipelinedGetSetBenchmark {
private static final int TOTAL_OPERATIONS = 200000;
public static void main(String[] args) throws UnknownHostException,
IOException {
Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort());
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
IOException {
Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort());
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
long begin = Calendar.getInstance().getTimeInMillis();
long begin = Calendar.getInstance().getTimeInMillis();
Pipeline p = jedis.pipelined();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n;
p.set(key, "bar" + n);
p.get(key);
}
p.sync();
Pipeline p = jedis.pipelined();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n;
p.set(key, "bar" + n);
p.get(key);
}
p.sync();
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
jedis.disconnect();
jedis.disconnect();
System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
}
}

View File

@@ -16,49 +16,49 @@ public class PoolBenchmark {
private static final int TOTAL_OPERATIONS = 100000;
public static void main(String[] args) throws Exception {
Jedis j = new Jedis(hnp.getHost(), hnp.getPort());
j.connect();
j.auth("foobared");
j.flushAll();
j.quit();
j.disconnect();
long t = System.currentTimeMillis();
// withoutPool();
withPool();
long elapsed = System.currentTimeMillis() - t;
System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
Jedis j = new Jedis(hnp.getHost(), hnp.getPort());
j.connect();
j.auth("foobared");
j.flushAll();
j.quit();
j.disconnect();
long t = System.currentTimeMillis();
// withoutPool();
withPool();
long elapsed = System.currentTimeMillis() - t;
System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
}
private static void withPool() throws Exception {
final JedisPool pool = new JedisPool(new GenericObjectPoolConfig(),
hnp.getHost(), hnp.getPort(), 2000, "foobared");
List<Thread> tds = new ArrayList<Thread>();
final JedisPool pool = new JedisPool(new GenericObjectPoolConfig(),
hnp.getHost(), hnp.getPort(), 2000, "foobared");
List<Thread> tds = new ArrayList<Thread>();
final AtomicInteger ind = new AtomicInteger();
for (int i = 0; i < 50; i++) {
Thread hj = new Thread(new Runnable() {
public void run() {
for (int i = 0; (i = ind.getAndIncrement()) < TOTAL_OPERATIONS;) {
try {
Jedis j = pool.getResource();
final String key = "foo" + i;
j.set(key, key);
j.get(key);
pool.returnResource(j);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
tds.add(hj);
hj.start();
}
final AtomicInteger ind = new AtomicInteger();
for (int i = 0; i < 50; i++) {
Thread hj = new Thread(new Runnable() {
public void run() {
for (int i = 0; (i = ind.getAndIncrement()) < TOTAL_OPERATIONS;) {
try {
Jedis j = pool.getResource();
final String key = "foo" + i;
j.set(key, key);
j.get(key);
pool.returnResource(j);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
tds.add(hj);
hj.start();
}
for (Thread t : tds)
t.join();
for (Thread t : tds)
t.join();
pool.destroy();
pool.destroy();
}
}

View File

@@ -0,0 +1,105 @@
package redis.clients.jedis.tests.benchmark;
import redis.clients.jedis.Protocol;
import redis.clients.util.RedisInputStream;
import redis.clients.util.RedisOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
/**
* Copyright (c) 2014
*/
public class ProtocolBenchmark {
private static final int TOTAL_OPERATIONS = 500000;
public static void main(String[] args) throws Exception,
IOException {
long total = 0;
for (int at = 0; at != 10; ++at) {
long elapsed = measureInputMulti();
long ops = ((1000 * 2 * TOTAL_OPERATIONS) / TimeUnit.NANOSECONDS.toMillis(elapsed));
if (at >= 5) {
total += ops;
}
}
System.out.println((total / 5) + " avg");
total = 0;
for (int at = 0; at != 10; ++at) {
long elapsed = measureInputStatus();
long ops = ((1000 * 2 * TOTAL_OPERATIONS) / TimeUnit.NANOSECONDS.toMillis(elapsed));
if (at >= 5) {
total += ops;
}
}
System.out.println((total / 5) + " avg");
total = 0;
for (int at = 0; at != 10; ++at) {
long elapsed = measureCommand();
long ops = ((1000 * 2 * TOTAL_OPERATIONS) / TimeUnit.NANOSECONDS.toMillis(elapsed));
if (at >= 5) {
total += ops;
}
}
System.out.println((total / 5) + " avg");
}
private static long measureInputMulti() throws Exception {
long duration = 0;
InputStream is = new ByteArrayInputStream(
"*4\r\n$3\r\nfoo\r\n$13\r\nbarbarbarfooz\r\n$5\r\nHello\r\n$5\r\nWorld\r\n"
.getBytes());
RedisInputStream in = new RedisInputStream(is);
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
long start = System.nanoTime();
Protocol.read(in);
duration += (System.nanoTime() - start);
in.reset();
}
return duration;
}
private static long measureInputStatus() throws Exception {
long duration = 0;
InputStream is = new ByteArrayInputStream(
"+OK\r\n"
.getBytes());
RedisInputStream in = new RedisInputStream(is);
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
long start = System.nanoTime();
Protocol.read(in);
duration += (System.nanoTime() - start);
in.reset();
}
return duration;
}
private static long measureCommand() throws Exception {
long duration = 0;
byte[] KEY = "123456789".getBytes();
byte[] VAL = "FooBar".getBytes();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
RedisOutputStream out = new RedisOutputStream(new ByteArrayOutputStream(8192));
long start = System.nanoTime();
Protocol.sendCommand(out, Protocol.Command.SET, KEY, VAL);
duration += (System.nanoTime() - start);
}
return duration;
}
}

View File

@@ -10,29 +10,29 @@ public class SafeEncoderBenchmark {
private static final int TOTAL_OPERATIONS = 10000000;
public static void main(String[] args) throws UnknownHostException,
IOException {
long begin = Calendar.getInstance().getTimeInMillis();
IOException {
long begin = Calendar.getInstance().getTimeInMillis();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
SafeEncoder.encode("foo bar!");
}
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
SafeEncoder.encode("foo bar!");
}
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed)
+ " ops to build byte[]");
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed)
+ " ops to build byte[]");
begin = Calendar.getInstance().getTimeInMillis();
begin = Calendar.getInstance().getTimeInMillis();
byte[] bytes = "foo bar!".getBytes();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
SafeEncoder.encode(bytes);
}
byte[] bytes = "foo bar!".getBytes();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
SafeEncoder.encode(bytes);
}
elapsed = Calendar.getInstance().getTimeInMillis() - begin;
elapsed = Calendar.getInstance().getTimeInMillis() - begin;
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed)
+ " ops to build Strings");
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed)
+ " ops to build Strings");
}
}

View File

@@ -10,30 +10,30 @@ public class ShardedBenchmark {
private static final int TOTAL_OPERATIONS = 10000000;
public static void main(String[] args) throws UnknownHostException,
IOException {
IOException {
long begin = Calendar.getInstance().getTimeInMillis();
long begin = Calendar.getInstance().getTimeInMillis();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n;
Hashing.MD5.hash(key);
}
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n;
Hashing.MD5.hash(key);
}
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " MD5 ops");
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " MD5 ops");
begin = Calendar.getInstance().getTimeInMillis();
begin = Calendar.getInstance().getTimeInMillis();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n;
Hashing.MURMUR_HASH.hash(key);
}
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n;
Hashing.MURMUR_HASH.hash(key);
}
elapsed = Calendar.getInstance().getTimeInMillis() - begin;
elapsed = Calendar.getInstance().getTimeInMillis() - begin;
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed)
+ " Murmur ops");
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed)
+ " Murmur ops");
}
}

View File

@@ -30,560 +30,560 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase {
@Test
public void ping() {
String status = jedis.ping();
assertEquals("PONG", status);
String status = jedis.ping();
assertEquals("PONG", status);
}
@Test
public void exists() {
String status = jedis.set("foo", "bar");
assertEquals("OK", status);
String status = jedis.set("foo", "bar");
assertEquals("OK", status);
status = jedis.set(bfoo, bbar);
assertEquals("OK", status);
status = jedis.set(bfoo, bbar);
assertEquals("OK", status);
boolean reply = jedis.exists("foo");
assertTrue(reply);
boolean reply = jedis.exists("foo");
assertTrue(reply);
reply = jedis.exists(bfoo);
assertTrue(reply);
reply = jedis.exists(bfoo);
assertTrue(reply);
long lreply = jedis.del("foo");
assertEquals(1, lreply);
long lreply = jedis.del("foo");
assertEquals(1, lreply);
lreply = jedis.del(bfoo);
assertEquals(1, lreply);
lreply = jedis.del(bfoo);
assertEquals(1, lreply);
reply = jedis.exists("foo");
assertFalse(reply);
reply = jedis.exists("foo");
assertFalse(reply);
reply = jedis.exists(bfoo);
assertFalse(reply);
reply = jedis.exists(bfoo);
assertFalse(reply);
}
@Test
public void del() {
jedis.set("foo1", "bar1");
jedis.set("foo2", "bar2");
jedis.set("foo3", "bar3");
jedis.set("foo1", "bar1");
jedis.set("foo2", "bar2");
jedis.set("foo3", "bar3");
long reply = jedis.del("foo1", "foo2", "foo3");
assertEquals(3, reply);
long reply = jedis.del("foo1", "foo2", "foo3");
assertEquals(3, reply);
Boolean breply = jedis.exists("foo1");
assertFalse(breply);
breply = jedis.exists("foo2");
assertFalse(breply);
breply = jedis.exists("foo3");
assertFalse(breply);
Boolean breply = jedis.exists("foo1");
assertFalse(breply);
breply = jedis.exists("foo2");
assertFalse(breply);
breply = jedis.exists("foo3");
assertFalse(breply);
jedis.set("foo1", "bar1");
jedis.set("foo1", "bar1");
reply = jedis.del("foo1", "foo2");
assertEquals(1, reply);
reply = jedis.del("foo1", "foo2");
assertEquals(1, reply);
reply = jedis.del("foo1", "foo2");
assertEquals(0, reply);
reply = jedis.del("foo1", "foo2");
assertEquals(0, reply);
// Binary ...
jedis.set(bfoo1, bbar1);
jedis.set(bfoo2, bbar2);
jedis.set(bfoo3, bbar3);
// Binary ...
jedis.set(bfoo1, bbar1);
jedis.set(bfoo2, bbar2);
jedis.set(bfoo3, bbar3);
reply = jedis.del(bfoo1, bfoo2, bfoo3);
assertEquals(3, reply);
reply = jedis.del(bfoo1, bfoo2, bfoo3);
assertEquals(3, reply);
breply = jedis.exists(bfoo1);
assertFalse(breply);
breply = jedis.exists(bfoo2);
assertFalse(breply);
breply = jedis.exists(bfoo3);
assertFalse(breply);
breply = jedis.exists(bfoo1);
assertFalse(breply);
breply = jedis.exists(bfoo2);
assertFalse(breply);
breply = jedis.exists(bfoo3);
assertFalse(breply);
jedis.set(bfoo1, bbar1);
jedis.set(bfoo1, bbar1);
reply = jedis.del(bfoo1, bfoo2);
assertEquals(1, reply);
reply = jedis.del(bfoo1, bfoo2);
assertEquals(1, reply);
reply = jedis.del(bfoo1, bfoo2);
assertEquals(0, reply);
reply = jedis.del(bfoo1, bfoo2);
assertEquals(0, reply);
}
@Test
public void type() {
jedis.set("foo", "bar");
String status = jedis.type("foo");
assertEquals("string", status);
jedis.set("foo", "bar");
String status = jedis.type("foo");
assertEquals("string", status);
// Binary
jedis.set(bfoo, bbar);
status = jedis.type(bfoo);
assertEquals("string", status);
// Binary
jedis.set(bfoo, bbar);
status = jedis.type(bfoo);
assertEquals("string", status);
}
@Test
public void keys() {
jedis.set("foo", "bar");
jedis.set("foobar", "bar");
jedis.set("foo", "bar");
jedis.set("foobar", "bar");
Set<String> keys = jedis.keys("foo*");
Set<String> expected = new HashSet<String>();
expected.add("foo");
expected.add("foobar");
assertEquals(expected, keys);
Set<String> keys = jedis.keys("foo*");
Set<String> expected = new HashSet<String>();
expected.add("foo");
expected.add("foobar");
assertEquals(expected, keys);
expected = new HashSet<String>();
keys = jedis.keys("bar*");
expected = new HashSet<String>();
keys = jedis.keys("bar*");
assertEquals(expected, keys);
assertEquals(expected, keys);
// Binary
jedis.set(bfoo, bbar);
jedis.set(bfoobar, bbar);
// Binary
jedis.set(bfoo, bbar);
jedis.set(bfoobar, bbar);
Set<byte[]> bkeys = jedis.keys(bfoostar);
assertEquals(2, bkeys.size());
assertTrue(setContains(bkeys, bfoo));
assertTrue(setContains(bkeys, bfoobar));
Set<byte[]> bkeys = jedis.keys(bfoostar);
assertEquals(2, bkeys.size());
assertTrue(setContains(bkeys, bfoo));
assertTrue(setContains(bkeys, bfoobar));
bkeys = jedis.keys(bbarstar);
bkeys = jedis.keys(bbarstar);
assertEquals(0, bkeys.size());
assertEquals(0, bkeys.size());
}
@Test
public void randomKey() {
assertEquals(null, jedis.randomKey());
assertEquals(null, jedis.randomKey());
jedis.set("foo", "bar");
jedis.set("foo", "bar");
assertEquals("foo", jedis.randomKey());
assertEquals("foo", jedis.randomKey());
jedis.set("bar", "foo");
jedis.set("bar", "foo");
String randomkey = jedis.randomKey();
assertTrue(randomkey.equals("foo") || randomkey.equals("bar"));
String randomkey = jedis.randomKey();
assertTrue(randomkey.equals("foo") || randomkey.equals("bar"));
// Binary
jedis.del("foo");
jedis.del("bar");
assertEquals(null, jedis.randomKey());
// Binary
jedis.del("foo");
jedis.del("bar");
assertEquals(null, jedis.randomKey());
jedis.set(bfoo, bbar);
jedis.set(bfoo, bbar);
assertArrayEquals(bfoo, jedis.randomBinaryKey());
assertArrayEquals(bfoo, jedis.randomBinaryKey());
jedis.set(bbar, bfoo);
jedis.set(bbar, bfoo);
byte[] randomBkey = jedis.randomBinaryKey();
assertTrue(Arrays.equals(randomBkey, bfoo)
|| Arrays.equals(randomBkey, bbar));
byte[] randomBkey = jedis.randomBinaryKey();
assertTrue(Arrays.equals(randomBkey, bfoo)
|| Arrays.equals(randomBkey, bbar));
}
@Test
public void rename() {
jedis.set("foo", "bar");
String status = jedis.rename("foo", "bar");
assertEquals("OK", status);
jedis.set("foo", "bar");
String status = jedis.rename("foo", "bar");
assertEquals("OK", status);
String value = jedis.get("foo");
assertEquals(null, value);
String value = jedis.get("foo");
assertEquals(null, value);
value = jedis.get("bar");
assertEquals("bar", value);
value = jedis.get("bar");
assertEquals("bar", value);
// Binary
jedis.set(bfoo, bbar);
String bstatus = jedis.rename(bfoo, bbar);
assertEquals("OK", bstatus);
// Binary
jedis.set(bfoo, bbar);
String bstatus = jedis.rename(bfoo, bbar);
assertEquals("OK", bstatus);
byte[] bvalue = jedis.get(bfoo);
assertEquals(null, bvalue);
byte[] bvalue = jedis.get(bfoo);
assertEquals(null, bvalue);
bvalue = jedis.get(bbar);
assertArrayEquals(bbar, bvalue);
bvalue = jedis.get(bbar);
assertArrayEquals(bbar, bvalue);
}
@Test
public void renameOldAndNewAreTheSame() {
try {
jedis.set("foo", "bar");
jedis.rename("foo", "foo");
fail("JedisDataException expected");
} catch (final JedisDataException e) {
}
try {
jedis.set("foo", "bar");
jedis.rename("foo", "foo");
fail("JedisDataException expected");
} catch (final JedisDataException e) {
}
// Binary
try {
jedis.set(bfoo, bbar);
jedis.rename(bfoo, bfoo);
fail("JedisDataException expected");
} catch (final JedisDataException e) {
}
// Binary
try {
jedis.set(bfoo, bbar);
jedis.rename(bfoo, bfoo);
fail("JedisDataException expected");
} catch (final JedisDataException e) {
}
}
@Test
public void renamenx() {
jedis.set("foo", "bar");
long status = jedis.renamenx("foo", "bar");
assertEquals(1, status);
jedis.set("foo", "bar");
long status = jedis.renamenx("foo", "bar");
assertEquals(1, status);
jedis.set("foo", "bar");
status = jedis.renamenx("foo", "bar");
assertEquals(0, status);
jedis.set("foo", "bar");
status = jedis.renamenx("foo", "bar");
assertEquals(0, status);
// Binary
jedis.set(bfoo, bbar);
long bstatus = jedis.renamenx(bfoo, bbar);
assertEquals(1, bstatus);
// Binary
jedis.set(bfoo, bbar);
long bstatus = jedis.renamenx(bfoo, bbar);
assertEquals(1, bstatus);
jedis.set(bfoo, bbar);
bstatus = jedis.renamenx(bfoo, bbar);
assertEquals(0, bstatus);
jedis.set(bfoo, bbar);
bstatus = jedis.renamenx(bfoo, bbar);
assertEquals(0, bstatus);
}
@Test
public void dbSize() {
long size = jedis.dbSize();
assertEquals(0, size);
long size = jedis.dbSize();
assertEquals(0, size);
jedis.set("foo", "bar");
size = jedis.dbSize();
assertEquals(1, size);
jedis.set("foo", "bar");
size = jedis.dbSize();
assertEquals(1, size);
// Binary
jedis.set(bfoo, bbar);
size = jedis.dbSize();
assertEquals(2, size);
// Binary
jedis.set(bfoo, bbar);
size = jedis.dbSize();
assertEquals(2, size);
}
@Test
public void expire() {
long status = jedis.expire("foo", 20);
assertEquals(0, status);
long status = jedis.expire("foo", 20);
assertEquals(0, status);
jedis.set("foo", "bar");
status = jedis.expire("foo", 20);
assertEquals(1, status);
jedis.set("foo", "bar");
status = jedis.expire("foo", 20);
assertEquals(1, status);
// Binary
long bstatus = jedis.expire(bfoo, 20);
assertEquals(0, bstatus);
// Binary
long bstatus = jedis.expire(bfoo, 20);
assertEquals(0, bstatus);
jedis.set(bfoo, bbar);
bstatus = jedis.expire(bfoo, 20);
assertEquals(1, bstatus);
jedis.set(bfoo, bbar);
bstatus = jedis.expire(bfoo, 20);
assertEquals(1, bstatus);
}
@Test
public void expireAt() {
long unixTime = (System.currentTimeMillis() / 1000L) + 20;
long unixTime = (System.currentTimeMillis() / 1000L) + 20;
long status = jedis.expireAt("foo", unixTime);
assertEquals(0, status);
long status = jedis.expireAt("foo", unixTime);
assertEquals(0, status);
jedis.set("foo", "bar");
unixTime = (System.currentTimeMillis() / 1000L) + 20;
status = jedis.expireAt("foo", unixTime);
assertEquals(1, status);
jedis.set("foo", "bar");
unixTime = (System.currentTimeMillis() / 1000L) + 20;
status = jedis.expireAt("foo", unixTime);
assertEquals(1, status);
// Binary
long bstatus = jedis.expireAt(bfoo, unixTime);
assertEquals(0, bstatus);
// Binary
long bstatus = jedis.expireAt(bfoo, unixTime);
assertEquals(0, bstatus);
jedis.set(bfoo, bbar);
unixTime = (System.currentTimeMillis() / 1000L) + 20;
bstatus = jedis.expireAt(bfoo, unixTime);
assertEquals(1, bstatus);
jedis.set(bfoo, bbar);
unixTime = (System.currentTimeMillis() / 1000L) + 20;
bstatus = jedis.expireAt(bfoo, unixTime);
assertEquals(1, bstatus);
}
@Test
public void ttl() {
long ttl = jedis.ttl("foo");
assertEquals(-2, ttl);
long ttl = jedis.ttl("foo");
assertEquals(-2, ttl);
jedis.set("foo", "bar");
ttl = jedis.ttl("foo");
assertEquals(-1, ttl);
jedis.set("foo", "bar");
ttl = jedis.ttl("foo");
assertEquals(-1, ttl);
jedis.expire("foo", 20);
ttl = jedis.ttl("foo");
assertTrue(ttl >= 0 && ttl <= 20);
jedis.expire("foo", 20);
ttl = jedis.ttl("foo");
assertTrue(ttl >= 0 && ttl <= 20);
// Binary
long bttl = jedis.ttl(bfoo);
assertEquals(-2, bttl);
// Binary
long bttl = jedis.ttl(bfoo);
assertEquals(-2, bttl);
jedis.set(bfoo, bbar);
bttl = jedis.ttl(bfoo);
assertEquals(-1, bttl);
jedis.set(bfoo, bbar);
bttl = jedis.ttl(bfoo);
assertEquals(-1, bttl);
jedis.expire(bfoo, 20);
bttl = jedis.ttl(bfoo);
assertTrue(bttl >= 0 && bttl <= 20);
jedis.expire(bfoo, 20);
bttl = jedis.ttl(bfoo);
assertTrue(bttl >= 0 && bttl <= 20);
}
@Test
public void select() {
jedis.set("foo", "bar");
String status = jedis.select(1);
assertEquals("OK", status);
assertEquals(null, jedis.get("foo"));
status = jedis.select(0);
assertEquals("OK", status);
assertEquals("bar", jedis.get("foo"));
// Binary
jedis.set(bfoo, bbar);
String bstatus = jedis.select(1);
assertEquals("OK", bstatus);
assertEquals(null, jedis.get(bfoo));
bstatus = jedis.select(0);
assertEquals("OK", bstatus);
assertArrayEquals(bbar, jedis.get(bfoo));
jedis.set("foo", "bar");
String status = jedis.select(1);
assertEquals("OK", status);
assertEquals(null, jedis.get("foo"));
status = jedis.select(0);
assertEquals("OK", status);
assertEquals("bar", jedis.get("foo"));
// Binary
jedis.set(bfoo, bbar);
String bstatus = jedis.select(1);
assertEquals("OK", bstatus);
assertEquals(null, jedis.get(bfoo));
bstatus = jedis.select(0);
assertEquals("OK", bstatus);
assertArrayEquals(bbar, jedis.get(bfoo));
}
@Test
public void getDB() {
assertEquals(0, jedis.getDB().longValue());
jedis.select(1);
assertEquals(1, jedis.getDB().longValue());
assertEquals(0, jedis.getDB().longValue());
jedis.select(1);
assertEquals(1, jedis.getDB().longValue());
}
@Test
public void move() {
long status = jedis.move("foo", 1);
assertEquals(0, status);
long status = jedis.move("foo", 1);
assertEquals(0, status);
jedis.set("foo", "bar");
status = jedis.move("foo", 1);
assertEquals(1, status);
assertEquals(null, jedis.get("foo"));
jedis.set("foo", "bar");
status = jedis.move("foo", 1);
assertEquals(1, status);
assertEquals(null, jedis.get("foo"));
jedis.select(1);
assertEquals("bar", jedis.get("foo"));
jedis.select(1);
assertEquals("bar", jedis.get("foo"));
// Binary
jedis.select(0);
long bstatus = jedis.move(bfoo, 1);
assertEquals(0, bstatus);
// Binary
jedis.select(0);
long bstatus = jedis.move(bfoo, 1);
assertEquals(0, bstatus);
jedis.set(bfoo, bbar);
bstatus = jedis.move(bfoo, 1);
assertEquals(1, bstatus);
assertEquals(null, jedis.get(bfoo));
jedis.set(bfoo, bbar);
bstatus = jedis.move(bfoo, 1);
assertEquals(1, bstatus);
assertEquals(null, jedis.get(bfoo));
jedis.select(1);
assertArrayEquals(bbar, jedis.get(bfoo));
jedis.select(1);
assertArrayEquals(bbar, jedis.get(bfoo));
}
@Test
public void flushDB() {
jedis.set("foo", "bar");
assertEquals(1, jedis.dbSize().intValue());
jedis.set("bar", "foo");
jedis.move("bar", 1);
String status = jedis.flushDB();
assertEquals("OK", status);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(1, jedis.dbSize().intValue());
jedis.del("bar");
jedis.set("foo", "bar");
assertEquals(1, jedis.dbSize().intValue());
jedis.set("bar", "foo");
jedis.move("bar", 1);
String status = jedis.flushDB();
assertEquals("OK", status);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(1, jedis.dbSize().intValue());
jedis.del("bar");
// Binary
jedis.select(0);
jedis.set(bfoo, bbar);
assertEquals(1, jedis.dbSize().intValue());
jedis.set(bbar, bfoo);
jedis.move(bbar, 1);
String bstatus = jedis.flushDB();
assertEquals("OK", bstatus);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(1, jedis.dbSize().intValue());
// Binary
jedis.select(0);
jedis.set(bfoo, bbar);
assertEquals(1, jedis.dbSize().intValue());
jedis.set(bbar, bfoo);
jedis.move(bbar, 1);
String bstatus = jedis.flushDB();
assertEquals("OK", bstatus);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(1, jedis.dbSize().intValue());
}
@Test
public void flushAll() {
jedis.set("foo", "bar");
assertEquals(1, jedis.dbSize().intValue());
jedis.set("bar", "foo");
jedis.move("bar", 1);
String status = jedis.flushAll();
assertEquals("OK", status);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(0, jedis.dbSize().intValue());
jedis.set("foo", "bar");
assertEquals(1, jedis.dbSize().intValue());
jedis.set("bar", "foo");
jedis.move("bar", 1);
String status = jedis.flushAll();
assertEquals("OK", status);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(0, jedis.dbSize().intValue());
// Binary
jedis.select(0);
jedis.set(bfoo, bbar);
assertEquals(1, jedis.dbSize().intValue());
jedis.set(bbar, bfoo);
jedis.move(bbar, 1);
String bstatus = jedis.flushAll();
assertEquals("OK", bstatus);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(0, jedis.dbSize().intValue());
// Binary
jedis.select(0);
jedis.set(bfoo, bbar);
assertEquals(1, jedis.dbSize().intValue());
jedis.set(bbar, bfoo);
jedis.move(bbar, 1);
String bstatus = jedis.flushAll();
assertEquals("OK", bstatus);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(0, jedis.dbSize().intValue());
}
@Test
public void persist() {
jedis.setex("foo", 60 * 60, "bar");
assertTrue(jedis.ttl("foo") > 0);
long status = jedis.persist("foo");
assertEquals(1, status);
assertEquals(-1, jedis.ttl("foo").intValue());
jedis.setex("foo", 60 * 60, "bar");
assertTrue(jedis.ttl("foo") > 0);
long status = jedis.persist("foo");
assertEquals(1, status);
assertEquals(-1, jedis.ttl("foo").intValue());
// Binary
jedis.setex(bfoo, 60 * 60, bbar);
assertTrue(jedis.ttl(bfoo) > 0);
long bstatus = jedis.persist(bfoo);
assertEquals(1, bstatus);
assertEquals(-1, jedis.ttl(bfoo).intValue());
// Binary
jedis.setex(bfoo, 60 * 60, bbar);
assertTrue(jedis.ttl(bfoo) > 0);
long bstatus = jedis.persist(bfoo);
assertEquals(1, bstatus);
assertEquals(-1, jedis.ttl(bfoo).intValue());
}
@Test
public void echo() {
String result = jedis.echo("hello world");
assertEquals("hello world", result);
String result = jedis.echo("hello world");
assertEquals("hello world", result);
// Binary
byte[] bresult = jedis.echo(SafeEncoder.encode("hello world"));
assertArrayEquals(SafeEncoder.encode("hello world"), bresult);
// Binary
byte[] bresult = jedis.echo(SafeEncoder.encode("hello world"));
assertArrayEquals(SafeEncoder.encode("hello world"), bresult);
}
@Test
public void dumpAndRestore() {
jedis.set("foo1", "bar1");
byte[] sv = jedis.dump("foo1");
jedis.restore("foo2", 0, sv);
assertTrue(jedis.exists("foo2"));
jedis.set("foo1", "bar1");
byte[] sv = jedis.dump("foo1");
jedis.restore("foo2", 0, sv);
assertTrue(jedis.exists("foo2"));
}
@Test
public void pexpire() {
long status = jedis.pexpire("foo", 10000);
assertEquals(0, status);
long status = jedis.pexpire("foo", 10000);
assertEquals(0, status);
jedis.set("foo1", "bar1");
status = jedis.pexpire("foo1", 10000);
assertEquals(1, status);
jedis.set("foo1", "bar1");
status = jedis.pexpire("foo1", 10000);
assertEquals(1, status);
jedis.set("foo2", "bar2");
status = jedis.pexpire("foo2", 200000000000L);
assertEquals(1, status);
jedis.set("foo2", "bar2");
status = jedis.pexpire("foo2", 200000000000L);
assertEquals(1, status);
long pttl = jedis.pttl("foo2");
assertTrue(pttl > 100000000000L);
long pttl = jedis.pttl("foo2");
assertTrue(pttl > 100000000000L);
}
@Test
public void pexpireAt() {
long unixTime = (System.currentTimeMillis()) + 10000;
long unixTime = (System.currentTimeMillis()) + 10000;
long status = jedis.pexpireAt("foo", unixTime);
assertEquals(0, status);
long status = jedis.pexpireAt("foo", unixTime);
assertEquals(0, status);
jedis.set("foo", "bar");
unixTime = (System.currentTimeMillis()) + 10000;
status = jedis.pexpireAt("foo", unixTime);
assertEquals(1, status);
jedis.set("foo", "bar");
unixTime = (System.currentTimeMillis()) + 10000;
status = jedis.pexpireAt("foo", unixTime);
assertEquals(1, status);
}
@Test
public void pttl() {
long pttl = jedis.pttl("foo");
assertEquals(-2, pttl);
long pttl = jedis.pttl("foo");
assertEquals(-2, pttl);
jedis.set("foo", "bar");
pttl = jedis.pttl("foo");
assertEquals(-1, pttl);
jedis.set("foo", "bar");
pttl = jedis.pttl("foo");
assertEquals(-1, pttl);
jedis.pexpire("foo", 20000);
pttl = jedis.pttl("foo");
assertTrue(pttl >= 0 && pttl <= 20000);
jedis.pexpire("foo", 20000);
pttl = jedis.pttl("foo");
assertTrue(pttl >= 0 && pttl <= 20000);
}
@Test
public void scan() {
jedis.set("b", "b");
jedis.set("a", "a");
jedis.set("b", "b");
jedis.set("a", "a");
ScanResult<String> result = jedis.scan(SCAN_POINTER_START);
ScanResult<String> result = jedis.scan(SCAN_POINTER_START);
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
// binary
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY);
// binary
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
}
@Test
public void scanMatch() {
ScanParams params = new ScanParams();
params.match("a*");
ScanParams params = new ScanParams();
params.match("a*");
jedis.set("b", "b");
jedis.set("a", "a");
jedis.set("aa", "aa");
ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params);
jedis.set("b", "b");
jedis.set("a", "a");
jedis.set("aa", "aa");
ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params);
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
// binary
params = new ScanParams();
params.match(bfoostar);
// binary
params = new ScanParams();
params.match(bfoostar);
jedis.set(bfoo1, bbar);
jedis.set(bfoo2, bbar);
jedis.set(bfoo3, bbar);
jedis.set(bfoo1, bbar);
jedis.set(bfoo2, bbar);
jedis.set(bfoo3, bbar);
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY,
params);
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY,
params);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
}
@Test
public void scanCount() {
ScanParams params = new ScanParams();
params.count(2);
ScanParams params = new ScanParams();
params.count(2);
for (int i = 0; i < 10; i++) {
jedis.set("a" + i, "a" + i);
}
for (int i = 0; i < 10; i++) {
jedis.set("a" + i, "a" + i);
}
ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params);
ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params);
assertFalse(result.getResult().isEmpty());
assertFalse(result.getResult().isEmpty());
// binary
params = new ScanParams();
params.count(2);
// binary
params = new ScanParams();
params.count(2);
jedis.set(bfoo1, bbar);
jedis.set(bfoo2, bbar);
jedis.set(bfoo3, bbar);
jedis.set(bfoo1, bbar);
jedis.set(bfoo2, bbar);
jedis.set(bfoo3, bbar);
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY,
params);
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY,
params);
assertFalse(bResult.getResult().isEmpty());
assertFalse(bResult.getResult().isEmpty());
}
}

Some files were not shown because too many files have changed in this diff Show More