Java EE project from 0 build (11): Integrate Redis in the project, for data storage or caching _redis

Source: Internet
Author: User
Tags connection pooling exception handling
First, Redis installation

Already installed Redis can go directly to the next step, no can be installed first: Linux (CentOS 7) Redis installation


Second, pom dependency: Jedis is a redis Java version of the client implementation

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId> spring-data-redis</artifactid>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactid>jedis</ artifactid>
			<version>2.6.1</version>
		</dependency>


Third, spring configuration

Create a new redis.properties in the Resources directory:

#redis setting
redis.hostname =192.168.240.131
redis.port=6379
redis.timeout=15000
redis.usepool =true
redis.password=buildmavenweb

#jedis setting
jedis.maxidle=6
jedis.minevictableidletimemillis=300000
jedis.numtestsperevictionrun=3
jedis.timebetweenevictionrunsmillis=60000

Create a Spring-redis.xml file again:
<?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:mvc= "Http://www.springframework.org/schema/mvc" xsi:schemalocation= "Http://www.springframework.org/schema /MVC http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/context http ://www.springframework.org/schema/context/spring-context.xsd "default-lazy-init= true" > <context: Component-scan base-package= "Com.spring.demo.redis"/> <!--introduced Redis profile--> <context: Property-placeholder location= "Classpath:redis.properties"/> <!--connection Pool configuration--> <bean id= "Jedispoolconfig" cl ass= "Redis.clients.jedis.JedisPoolConfig" > <!--the maximum number of idle connections in the connection pool--> <property name= "Maxidle" vaLue= "${jedis.maxidle}" ></property> <!--the minimum time that a connection is idle, the idle connection may be removed when this value is reached. A negative value (-1) means no removal. --> <property name= "Minevictableidletimemillis" value= "${jedis.minevictableidletimemillis}" ></ Property> <!--the number of linked resources per detection for the free link detection thread. The default is 3--> <property name= "Numtestsperevictionrun" value= "${jedis.numtestsperevictionrun}" ></property > <!--"free link" detection thread, the period of detection, the number of milliseconds. A negative value indicates that the detect thread is not running. The default is-1. --> <property name= "Timebetweenevictionrunsmillis" value= "${jedis.timebetweenevictionrunsmillis}" ></ Property> </bean> <!--spring provides Redis connection factory--> <bean id= "Jedisconnectionfactory" class= Amework.data.redis.connection.jedis.JedisConnectionFactory "destroy-method=" Destroy > <!--connection pool configuration--> < Property Name= "Poolconfig" ref= "Jedispoolconfig" ></property> <!--Redis Service host--> <property name= "hos Tname "value=" ${redis.hostname} "></property> <!--Redis service port number--> <property NAMe= "Port" value= "${redis.port}" ></property> <!--even timeout setting--> <property name= "Timeout" value=. Timeout} "></property> <!--whether to use connection pooling--> <property name=" Usepool "value=" ${redis.usepool} "></ property> <!--redis Service connection password--> <property name= "password" value= "${redis.password}" ></property> & Lt;/bean> <!--spring provides access to Redis classes--> <bean id= "Redistemplate" Org.springframework.data.redis.core.RedisTemplate "> <!--redis connection factory--> <property name=" ConnectionFactory "ref=" jedisconnectionfactory "></property> <property name=" Keyserializer "> < Bean class= "Org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <!-- Jdkserializationredisserializer supports serialization of all classes that implement serializable--> <property name= "ValueSerializer" > <bean class= "Org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property&Gt
 </bean> </beans>


PS: The following section is taken from: http://shift-alt-ctrl.iteye.com/blog/1887370

Spring-data-redis offers a variety of serializer strategies that are very handy for developers who use Jedis. The SDR provides 4 built-in Serializer:jdkserializationredisserializer: A serialization tool using JDK (Serializable interface, Objectinputstrean, ObjectOutputStream), data stored in byte stream stringredisserializer: string encoding, data stored in string Jacksonjsonredisserializer:json format Oxmserializer:xml Format Storage

Among them, Jdkserializationredisserializer and Stringredisserializer are the most basic serialization strategies, in which "Jacksonjsonredisserializer" and " Oxmserializer "are all based on stirng storage, so they are more" advanced "serialization (eventually using string parsing and building Java objects).

In Redistemplate, you need to declare 4 serializer, default to "Jdkserializationredisserializer":

1) Keyserializer: For ordinary k-v operations, key to take the serialization strategy
2) The serialization strategy adopted by Valueserializer:value
3) Hashkeyserializer: In the hash data structure, the Hash-key serialization strategy
4) serialization strategy for Hashvalueserializer:hash-value

In any case, it is recommended that Key/hashkey adopt Stringredisserializer.
Four, web.xml if the configuration file is a unified format loaded, such as: Classpath:/spring-*.xml, you are not allowed to do special loading, or you need to load the spring-redis.xml alone in

	<!--load configuration file-->
	<!--contextconfiglocation The default value in the Contextloaderlistener class is/web-inf/ Applicationcontext.xml-->
	<context-param>
		<param-name>contextconfiglocation</ param-name>
		<param-value>
			classpath:/spring-*.xml
		</param-value>
	</ Context-param>

Five, use in Java code

Create a new Redisutils.class that specializes in handling Redis related actions:

Package Com.spring.demo.redis;

Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.data.redis.core.RedisTemplate;
Import org.springframework.stereotype.Component;

/**
 * Created by Ehsy_it on 2016/8/7.
 * *
@Component public
class Redisutils {

    @Autowired
    private redistemplate<string,object> Redistemplate;

    /**
     * Gets the specified key value of value
     * @param key *
     /public Object gets
    (String key) {
        return Redistemplate.boundvalueops (Key). get ();

    /**
     * Saves the specified key value of value
     * @param key
     * @param value *
     /public
    void Set (String key, Object value) { C23/>redistemplate.boundvalueops (Key). Set (value);

    /**
     * Delete the value of the specified key
     * @param key/public
    void del (String key) {
        redistemplate.delete (key);
    }
}


VI. Testing a new Redismain.class class, we store a string and list type from the code and get it from:

Package Com.spring.demo.redis;

Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

Import java.util.ArrayList;
Import java.util.List;

/**
 * Created by Ehsy_it on 2016/8/7.
 */Public
class Redismain {public

    static void Main (string[] args) {
        ApplicationContext ctx = new Classpathxml ApplicationContext ("/spring-redis.xml");
        Redisutils redisutils = (redisutils) ctx.getbean ("Redisutils");
        Redisutils.set ("China", "porcelain");
        list<string> list = new arraylist<string> ();
        List.add ("a");
        List.add ("B");
        List.add ("C");
        Redisutils.set ("list", list);
        System.out.println ("china=" + redisutils.get ("the");
        System.out.println ("list[1]=" + ((list) redisutils.get ("List")). Get (1));
    }





Vii. exception handling integration encountered problems can be viewed here Resolved: Redis Exception Summary (continuous collection); or leave a message for us to discuss together.
Eight, recommended Redis study address: http://www.redis.net.cn/
=============================================================================================================== ======= in order to facilitate everyone to learn, the project will be open source on my GitHub: Project address: Https://github.com/gubaijin/buildmavenweb
How to GitHub the project Open source channel, see my other blog post: GitHub Create project and initialize local project submit to GitHub






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.