Spring Consolidated Redis Sentinel implements Redis ha service invocation __spring

Source: Internet
Author: User
Tags aop getmessage redis

First, Redis-sentinel ha framework to build

For a detailed setup process, please refer to another article with the following address:

Click to open the link

Second, the introduction of a dependent jar package

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

Third, spring configuration file

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns:
Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns: p= "http://www.springframework.org/schema/p" xmlns:cache= "Http://www.springframework.org/schema/cache" xmlns:jpa= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA" xsi:schemalocation= "http://www.springframework.org/schema/ Beans Http://www.springframework.org/schema/beans/spring-beans-3.1.xsd Http://www.springframewor K.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http:/   
          /WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.1.xsd Http://www.springframework.org/schema/tx Http://www.springframewoRk.org/schema/tx/spring-tx-3.1.xsd Http://www.springframework.org/schema/cache Http://www.springframe Work.org/schema/cache/spring-cache-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA HTTP://WWW.S
Pringframework.org/schema/data/jpa/spring-jpa-1.3.xsd "> <!--scan annotation package--> <context:annotation-config/> <context:component-scan base-package= "Com.chhliu.redis" ></context:component-scan> <!--
Load properties file--> <bean class= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
<property name= "Locations" > <list> <value>classpath:redis.properties</value> </list> </property> </bean> <bean id= "Jedispoolconfig" class= "Redis.clients.jedis.JedisPoolConfig" > <
Property Name= "Maxtotal" value= "${redis.maxtotal}" ></property> </bean> <!--configuration Sentinel Sentinel--> <bean id= "Redissentinel" class= "Redis.clients.jedis.JedisSentinelPool" >; Constructor-arg index= "0" value= "MyMaster"/> <constructor-arg index= "1" > <set> <value>${ Redis.sentinel.host1}:${redis.sentinel.port1}</value> <value>${redis.sentinel.host2}:${
Redis.sentinel.port2}</value> <value>${redis.sentinel.host3}:${redis.sentinel.port3}</value> </set> </constructor-arg> <constructor-arg index= "2" ref= "Jedispoolconfig"/> </bean> </ Beans>

Iv. redis.properties configuration Files

redis.maxtotal=100
redis.sentinel.host1=127.0.0.1
redis.sentinel.host2=127.0.0.1
redis.sentinel.host3=127.0.0.1
redis.sentinel.port1=26379
redis.sentinel.port2=26479
redis.sentinel.port3=26579

V. Defining Interface Services

Defining callback Interfaces

/**
 * Description: Redis Connection Callback Interface * * Public
Interface Connectioncallback<t, p> {
	/**
	 * Details: Connection Redis Service
	 * @param shardedjedis Jedis fragment
	 * @return
	 * t
	/t Doinconnection (P p) throws redisoperationexception;
}
Define the methods provided by the interface

Public interface Redisoperations {/** * Details: Execute callback Service/T Execute (connectioncallback<t, jedis> action
) throws Redisoperationexception;
/** * Details: Set key-value/String set (final string key, final string value) throws Redisoperationexception; /** * Details: Sets the key-value pair and sets the expiration time of the key/string set (final string key, final string value, Final int expiretime) throws Redisope
Rationexception;
/** * Details: Gets the value of the specified key */String Get (Final String key) throws redisoperationexception;
/** * Details: Delete the specified key */Long del (final String key) throws redisoperationexception;
/** * Details: Gets the set of key values * * * set<string> keys (final String Keypattern) throws redisoperationexception;
/** * Details: To determine whether the current key exists * * Boolean exist (final String key) throws redisoperationexception; /** * Attention:list Paging operation * * list<string> Lrange (final String key, final long start, final long end) throws Redisop
Erationexception; /** * Details: List add element */Long Rpush (final string key, final string ... valUES) throws Redisoperationexception; }

Six, service encapsulation

@Service ("Redistemplate") public class Redistemplate implements Redisoperations {@Resource (name = "Redissentinel")
Private Jedissentinelpool Jedissentinelpool; @Override public <T> T Execute (connectioncallback<t, jedis> action) throws Redisoperationexception {Jedis JE
dis = null;
try {//Get Jedis Sentinel resource from connection pool Jedis = Jedissentinelpool.getresource ();//Execute callback method return Action.doinconnection (Jedis); catch (Exception e) {throw new Redisoperationexception (E, "Redis Service failed!");} finally {if (null!= Jedis) {JE
Dis.close (); @Override public boolean exist (final String key) throws Redisoperationexception {return execute (new CONNECTIONCALLB Ack<boolean, jedis> () {@Override public Boolean doinconnection (Jedis Jedis) throws Redisoperationexception {retur
n jedis.exists (key);
}
}); @Override public string Set (final string key, final string value) throws Redisoperationexception {return execute (new Co Nnectioncallback<string, jedis> () {@Override public String doinconnection (Jedis Jedis) throws Redisoperationexception {try{return Jedis.set (key, value); 
catch (Exception e) {throw new Redisoperationexception (E, "write to Redis Failed!key:" + key + "value:" + value);}}); @Override public string Set (final string key, final string value, Final int expiretime) throws Redisoperationexception {return execute (new connectioncallback<string, jedis> () {@Override public String doinconnection (Jedis Jedis) thro  WS Redisoperationexception {try {String result = Jedis.set (key, value); Jedis.expire (key, Expiretime);
catch (Exception e) {throw new Redisoperationexception (E, "write to Redis Failed!key:" + key + "value:" + value);}
}); @Override public string Get (final String key) throws Redisoperationexception {return execute (new connectioncallback<  String, jedis> () {@Override public string doinconnection (Jedis Jedis) throws Redisoperationexception {Boolean isexist
= exist (key); if (isexist) {return Jedis.Get (key);
return null;
}
}); @Override public Long del (final String key) throws Redisoperationexception {return execute (new Connectioncallback<lo Ng, Jedis> () {@Override public Long doinconnection (Jedis Jedis) throws Redisoperationexception {Boolean isexist = Exi
St (key);
if (isexist) {return Jedis.del (key);
}
}); @Override public set<string> keys (final String Keypattern) throws Redisoperationexception {return execute (new Con
Nectioncallback<set<string&gt, jedis> () {@Override public set<string> doinconnection (Jedis Jedis) {
set<string> sets = Jedis.keys (Keypattern);
return sets;
}
}); @Override Public list<string> lrange (final String key, final long start, final long end) throws Redisoperationexce ption {return execute (new Connectioncallback<list<string>, jedis> () {@Override public list<string>
Doinconnection (Jedis Jedis) throws Redisoperationexception {return Jedis.lrange (key, start, end);}}); } @OveRride Public long Rpush (final string key, final string ... values) throws Redisoperationexception {return execute (new Conn
Ectioncallback<long, jedis> () {@Override public Long doinconnection (Jedis Jedis) throws Redisoperationexception {
Return Jedis.rpush (key, values);
}
}); }
}

If you need to use other methods in the project, add the corresponding method directly with the callback mechanism above, of course, if you feel that your encapsulation method is troublesome, you can also use the spring data Redis directly, this is more comprehensive, if we only use a small number of methods in the project, Or suggest that you encapsulate it.

Seven, service test

@RunWith (Springjunit4classrunner.class)
@ContextConfiguration (locations = {"Classpath: Applicationcontext-redis.xml "}" public
class Redistemplatetest {
@Resource (name = "Redistemplate")
Private Redistemplate redistemplate;
@Test public
void Testset () {
try {
redistemplate.set ("1234567", "7890",);
} catch ( Redisoperationexception e) {
System.out.println (e.getmessage ());
}
}
@Test public
void Testget () {
try {
System.out.println (redistemplate.get ("1234567"));
} catch ( Redisoperationexception e) {
System.out.println (e.getmessage ());}}}
Related Article

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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