Configuration of Redis under Spring

Source: Internet
Author: User
Tags delete key redis server

This project uses Redis, so I learned how to configure Redis under the Spring framework.

1, the first is to add the spring configuration file in Web. Xml.

<web-app version= "3.0" xmlns= "Http://java.sun.com/xml/ns/javaee"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" > <display-name> Common design</display-name> <context-param> <param-name>webapprootkey</param-name&gt          ; <param-value>webapp.root</param-value> </context-param> <!--add a spring mybatis configuration file--&gt    ; <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpat H:applicationcontext.xml,classpath*:mybatis-config.xml</param-value> </context-param> <listener > <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-va lue>classpath:springmvc-servlet.xml</param-value> </init-param> </servlet> <servlet-mappi Ng> <servlet-name>springmvc</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping></web-app>

2. Then the Redis configuration file (redis-config.xml) file.

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation="http//Www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp//Www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp://www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp//Www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsd"    default-autowire= "ByName"default-lazy-init= "true" > <bean id= "Poolconfig"class= "Redis.clients.jedis.JedisPoolConfig" > <property name= "maxidle" value= "${redis.maxidle}"/> &LT;PR Operty name= "Maxwaitmillis" value= "${redis.maxwait}"/> <property name= "Testonborrow" value= "${redis.testOnBo Rrow} "/> </bean> <!--redis Server Center--<bean id=" ConnectionFactory "class= "Org.springframework.data.redis.connection.jedis.JedisConnectionFactory" > <property name= "poolconfig" ref= "Poolconfig"/> <property name= "port" value= "${redis.port}"/> <property name= "HostName" value= " ${redis.host} "/> <property name=" password "value=" ${redis.password} "/> <property name=" Timeout "Value=" ${redis.timeout} "></property> </bean> <bean id=" Redistemplate "class= "Org.springframework.data.redis.core.RedisTemplate" > <property name= "connectionfactory" ref= " ConnectionFactory "/> <property name=" Keyserializer "> <Beanclass= "Org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property Name = "ValueSerializer" > <Beanclass= "Org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property> &LT;/BEAN&G    T <bean id= "Redisutil"class= "Com.zkxl.fep.redis.RedisUtil" > <property name= "redistemplate" ref= "Redistemplate"/> </bean>&lt ;/beans>

Referencing the Redis profile in spring's configuration file

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation="http//Www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp//Www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp://www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp//Www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsd"    default-autowire= "ByName"default-lazy-init= "true" > <context:annotation-config/> <context:component-scan base- Package= "Com.test.fep"/> <!--increased Redis properties file--<context:property-placeholder location= "classpath*: Jdbc.properties,classpath*:redis.properties "/> <ImportResource= "Datasource.xml"/> <!--importing Redis profiles--<ImportResource= "Redis-config.xml"/> </beans>

3. New redis.properties, which contains configuration information required for Redis connection

#redis setting  redis.host=127.0.0.1redis.port=6379redis.password=123456  Redis.maxidle=100redis.maxactive=300redis.maxwait=1000redis.testonborrow=  Trueredis.timeout=100000=10000

Be sure to note that there are no spaces behind each line, and I'm stuck with this problem for one or two hours = =

4, write Redisutil.java, inside put Redis's additions and deletions to change the operation.

 PackageCom.test.fep.redis;Importjava.io.Serializable; ImportJava.util.Set; ImportJava.util.concurrent.TimeUnit; Importorg.springframework.data.redis.core.RedisTemplate; Importorg.springframework.data.redis.core.ValueOperations;  Public classRedisutil {PrivateRedistemplate<serializable, object>redistemplate; /*** Bulk Delete the corresponding value * *@paramKeys*/     Public voidRemoveFinalString ... keys) {         for(String key:keys) {remove (key); }    }    /*** Bulk Delete key * *@parampattern*/     Public voidRemovepattern (FinalString pattern) {Set<Serializable> keys =Redistemplate.keys (pattern); if(Keys.size () > 0) Redistemplate.delete (keys); }    /*** Delete the corresponding value * *@paramKey*/     Public voidRemoveFinalString Key) {        if(Exists (key)) {Redistemplate.delete (key); }    }    /*** Determine if there is a corresponding value in the cache * *@paramKey *@return     */     Public BooleanExistsFinalString Key) {        returnRedistemplate.haskey (key); }    /*** Read Cache * *@paramKey *@return     */     PublicObject Get (FinalString Key) {Object result=NULL; Valueoperations<serializable, object> operations =Redistemplate.opsforvalue (); Result=Operations.get (key); returnresult; }    /*** Write Cache * *@paramKey *@paramValue *@return     */     Public BooleanSetFinalString key, Object value) {        Booleanresult =false; Try{valueoperations<serializable, object> operations =Redistemplate.opsforvalue ();            Operations.set (key, value); Result=true; } Catch(Exception e) {logger.error ("Set Cache Error", E); }        returnresult; }    /*** Write Cache * *@paramKey *@paramValue *@return     */     Public BooleanSetFinalString Key, Object value, Long expiretime) {        Booleanresult =false; Try{valueoperations<serializable, object> operations =Redistemplate.opsforvalue ();            Operations.set (key, value);            Redistemplate.expire (Key, Expiretime, timeunit.seconds); Result=true; } Catch(Exception e) {logger.error ("Set Cache Error", E); }        returnresult; }         Public LongIncrementFinalString Key,LongDelta) {         returnredistemplate.opsforvalue (). Increment (key, delta); }     Public voidSetredistemplate (redistemplate<serializable, object>redistemplate) {         This. redistemplate =redistemplate; }}

5. Call the method in the Redisutil class in the function code,

 PackageCom.test.fep.service.impl;ImportJava.math.BigDecimal;Importjava.util.Date;Importjava.util.List;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Service;ImportCom.test.fep.domain.SysAppLoginToken;ImportCom.test.fep.mapper.SysAppLoginTokenMapper;ImportCom.test.fep.redis.RedisUtil;ImportCom.test.fep.service.AuthService;Importnet.sf.json.JSONObject; @Service ("Authservice") Public classAuthserviceimplImplementsauthservice{@AutowiredPrivateSysapplogintokenmapper Sysapplogintokenmapper; @AutowiredPrivateRedisutil Redisutil;//Remember to inject@Override Publicsysapplogintoken Verification (String Tokenid) {Sysapplogintoken token=NULL; if(Redisutil.exists (Tokenid)) {token= (Sysapplogintoken) redisutil.get (Tokenid);//find tokens from the cache}Else{token=Sysapplogintokenmapper.selectbyprimarykey (Tokenid);    Redisutil.set (Tokenid, token); //Write token to cache        }                return NULL; }}

All right, here's a complete use of Redis in a project.

It is also important to note that all interfaces that are stored in Redis must implement the Serializable interface

Configuration of Redis under Spring

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.