First, Redis understand
1.1, Redis Introduction:
Redis is a key-value storage system. Like memcached, it supports a relatively larger number of stored value types, including string (string), list (linked list), set (set), Zset (sorted set– ordered set), and hash (hash type). These data types support Push/pop, Add/remove and intersection-set and differential sets and richer operations, and these operations are atomic. On this basis, Redis supports a variety of different ways of ordering. As with memcached, data is cached in memory to ensure efficiency. The difference is that Redis periodically writes the updated data to the disk or writes the modification operation to the appended record file, and on this basis, it realizes the Master-slave (master-slave) synchronization.
The Redis database is fully in memory and uses the disk for persistence only. Redis has a richer set of data types than many key-value data stores. Redis can copy data to any number of servers.
1.2, Redis Advantages:
(1) Exceptionally fast: the speed of Redis is very fast, can perform about 110,000 sets per second, about 81000 + records per second.
(2) Support rich data types: Redis support Most developers already know like lists, collections, ordered collections, hash data types. This makes it very easy to solve a wide variety of problems because we know which problems can be handled better by its data type.
(3) The operation is atomic: All Redis operations are atomic, which ensures that if two clients simultaneously access the Redis server, the updated value will be obtained.
(4) Multifunction utility: Redis is a versatile tool that can be used in multiple applications such as caching, message, queue use (Redis native support publish/subscribe), any transient data, application, such as Web application sessions, Web page hit count, etc.
1.3, Redis Disadvantage:
(1) Single thread
(2) Memory consumption
Two, 64-bit Windows Redis installation
Redis officially does not support Windows, but Microsoft Open Tech Group has developed a Win64 version on GitHub, download address: https://github.com/MSOpenTech/redis/releases. Note Only support for 64-bit ha.
The Small Treasure Pigeon is downloaded redis-x64-3.0.500.msi for installation. All the defaults can be taken during the installation process.
After the installation has been completed may have helped you to open the Redis corresponding service, the blogger is so. View resource management as follows, instructions are open:
The corresponding service has been opened, let's keep it, the following example needs to be used. If not, we command to open, enter the Redis installation directory (the blogger is C:\Program Files\redis), and then open the following command:
Redis-server redis.windows.conf
OK, let's do the example below.
Third, detailed examples
Environment used in this project: Eclipse + maven + Spring + junit
3.1, add dependent (Spring+junit+redis dependent), Pom.xml:
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < Modelversion>4.0.0</modelversion> <groupId>com.luo</groupId> <artifactid>redis_ Project</artifactid> <version>0.0.1-SNAPSHOT</version> <properties> <!--spring version
; <spring.version>3.2.8.RELEASE</spring.version> <!--junit version number--> <junit.version>4.10</ Junit.version> </properties> <dependencies> <!--add Spring dependencies--> <dependency> <gro Upid>org.springframework</groupid> <artifactId>spring-core</artifactId> <version>${ spring.version}</version> </dependency> <dependency> <groupid>org.springframework</ Groupid> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework </groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</ version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifa Ctid>spring-context-support</artifactid> <version>${spring.version}</version> </ dependency> <dependency> <groupId>org.springframework</groupId> <ARTIFACTID>SPRING-AOP </artifactId> <version>${spring.version}</version> </dependency> <dependency> < Groupid>org.springframework</groupid> <artifactId>spring-aspects</artifactId> <version >${spring.version}</version> </dependency> <dependency> <groupid>org.springframework& Lt;/groupid> <artifactid>spring-tx</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>or G.springframework</groupid> <artifactId>spring-jdbc</artifactId> <version>${ spring.version}</version> </dependency> <dependency> <groupid>org.springframework</ Groupid> <artifactId>spring-web</artifactId> <version>${spring.version}</version> < /dependency> <!--unit test dependencies--> <dependency> <groupId>junit</groupId> <artifactid> ;junit</artifactid> <version>${junit.version}</version> <scope>test</scope> </de
pendency> <!--spring Unit test dependencies--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope> Test</scope> </dependency> <!-- Redis dependent--> <dependency> <groupId>org.springframework.data</groupId> <artifactid>sp Ring-data-redis</artifactid> <version>1.6.1.RELEASE</version> </dependency> < dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <versio
n>2.7.3</version> </dependency> </dependencies> </project>
3.2, Spring configuration file Application.xml:
<?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" xsi:schemalocation= "Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/
AOP http://www.springframework.org/schema/aop/spring-aop-3.0.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!--automatically scan annotations for bean--> <context: Component-scan base-package= "Com.luo.service"/> <!--Introduce properties profile--> <bean id= "Propertyconfigurer" class= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > <property name= "Locations" > <list> <VALUE>CLASSPATH:PROPERTIES/*.PROperties</value> <!--If you have multiple profiles, just keep adding them here--> </list> </property> </bean> < !--Jedis configuration--> <bean id= "Poolconfig" class= "Redis.clients.jedis.JedisPoolConfig" > <property name= "Maxid" Le "value=" ${redis.maxidle} "/> <property name=" Maxwaitmillis "value=" ${redis.maxwait} "/> <property nam E= "Testonborrow" value= "${redis.testonborrow}"/> </bean > <!--redis Server center--> <bean id= "Connection Factory "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}"/>--> <propert Y name= "timeout" value= "${redis.timeout}" ></property> </bean > <bean id= "redistemplate" Org.springframework.data.redis.core.rEdistemplate "> <property name=" connectionfactory ref= "ConnectionFactory"/> <property name= "KeySeriali
Zer "> <bean class=" Org.springframework.data.redis.serializer.StringRedisSerializer "/> </property> <property name= "ValueSerializer" > <bean class= "Org.springframework.data.redis.serializer.JdkSerializatio" Nredisserializer "/> </property> </bean > <!--cache configuration--> <bean id=" Methodcacheintercepto R "class=" Com.luo.redis.cache.MethodCacheInterceptor "> <property name=" redistemplate "ref=" Redistemplate " > </bean > <!--AOP configuration pointcuts and notifications--> <bean id= "methodcachepointcut" class= "Org.springframework.aop.suppor" T.regexpmethodpointcutadvisor "> <property name=" Advice "ref=" Methodcacheinterceptor "/> <property-name=" Pattern "value=" *serviceimpl.*gettimestamp "/> </bean> <bean id=" Redistestservice "class=" Com.luo.service.impl.RedisTestServiceImpl ">;/bean> <bean class= "Org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/> </
Beans>
3.3, Redis configuration parameters, Redis.properties:
#redis中心
#绑定的主机地址
redis.host=127.0.0.1
#指定Redis监听端口, the default port is 6379
redis.port=6379
# Authorization password (not used in this example)
redis.password=123456
#最大空闲数: When the number of free links is greater than Maxidle, the recycle
redis.maxidle=100
# Maximum number of connections: can be established at the same time "maximum number of links"
redis.maxactive=300
#最大等待时间: Unit ms
redis.maxwait=1000
#使用连接时, detect the success of the connection
redis.testonborrow=true
#当客户端闲置多长时间后关闭连接, if specified as 0, to turn off the feature
redis.timeout=10000
3.4, add the interface and the corresponding implementation of Redistestservice.java and Redistestserviceimpl.java:
Package com.luo.service;
Public interface Redistestservice {public
string Gettimestamp (string param);
}
Package Com.luo.service.impl;
Import Org.springframework.stereotype.Service;
Import Com.luo.service.RedisTestService;
@Service public
class Redistestserviceimpl implements Redistestservice {public
string Gettimestamp (string param) {
Long timestamp = System.currenttimemillis ();
return timestamp.tostring ();
}
3.5. This example uses the spring AOP slice method for caching, configured in the spring configuration file above, corresponding to Methodcacheinterceptor.java:
Package Com.luo.redis.cache;
Import java.io.Serializable;
Import Java.util.concurrent.TimeUnit;
Import Org.aopalliance.intercept.MethodInterceptor;
Import org.aopalliance.intercept.MethodInvocation;
Import Org.springframework.data.redis.core.RedisTemplate;
Import org.springframework.data.redis.core.ValueOperations; public class Methodcacheinterceptor implements Methodinterceptor {private redistemplate<serializable, object> re
Distemplate; Private Long defaultcacheexpiretime = 10l;
The default expiration time is cached, where the 10-second public Object invoke (Methodinvocation invocation) throws Throwable {Object value = NULL is set.
String targetName = Invocation.getthis (). GetClass (). GetName ();
String methodname = Invocation.getmethod (). GetName ();
object[] arguments = invocation.getarguments ();
String key = Getcachekey (TargetName, MethodName, arguments);
try {//To determine if there is a cached if (exists (key)) {return GetCache (key);
}//write Cache value = Invocation.proceed (); if (value!= null) {
Final String TKey = key;
Final Object TValue = value;
New Thread (New Runnable () {public void run () {Setcache (TKey, TValue, defaultcacheexpiretime);
}). Start ();
} catch (Exception e) {e.printstacktrace ();
if (value = = null) {return invocation.proceed ();
} return value; /** * Create Cache Key * * @param targetName * @param methodname * @param arguments/private String Getcachekey (String targetName, String methodname, object[] arguments)
{StringBuffer SBU = new StringBuffer ();
Sbu.append (TargetName). Append ("_"). Append (methodname); if ((arguments!= null) && (arguments.length!= 0)) {for (int i = 0; i < arguments.length; i++) {sbu.a
Ppend ("_"). Append (Arguments[i]);
} return sbu.tostring (); /** * To determine if there is a corresponding value in the cache * * @param key * @return/public Boolean exists (final String key) {return red
Istemplate.haskey (key); /** * Read Cache * * @param key *@return */Public Object GetCache (final String key) {Object result = null;
Valueoperations<serializable, object> operations = redistemplate. Opsforvalue ();
result = Operations.get (key);
return result; /** * Write Cache * * @param key * @param value * @return/public boolean Setcache (final String key, Object
Value, Long expiretime) {Boolean result = false;
try {valueoperations<serializable, object> operations = redistemplate. Opsforvalue ();
Operations.set (key, value);
Redistemplate.expire (Key, Expiretime, timeunit.seconds);
result = true;
catch (Exception e) {e.printstacktrace ();
return result; } public void Setredistemplate (redistemplate<serializable, object> redistemplate) {this.redistemplate = re
Distemplate; }
}
3.6, unit test related classes:
Package com.luo.baseTest;
Import Org.junit.runner.RunWith;
Import org.springframework.test.context.ContextConfiguration;
Import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
Specifies @ContextConfiguration of the configuration file injected by the bean
(locations = {"Classpath:application.xml"})
//Use standard JUnit @ Runwith comment to tell JUnit to use the spring Testrunner
@RunWith (springjunit4classrunner.class) public
class Springtestcase Extends Abstractjunit4springcontexttests {
}
Package com.luo.service;
Import Org.junit.Test;
Import org.springframework.beans.factory.annotation.Autowired;
Import Com.luo.baseTest.SpringTestCase;
public class Redistestservicetest extends Springtestcase {
@Autowired
private Redistestservice Redistestservice;
@Test public
void Gettimestamptest () throws interruptedexception{
System.out.println ("First Call:" + Redistestservice.gettimestamp ("param"));
Thread.Sleep ();
System.out.println ("2 seconds after the call:" + redistestservice.gettimestamp ("param"));
Thread.Sleep (11000);
System.out.println ("Call after 11 seconds:" + redistestservice.gettimestamp ("param"));
}
3.7. Operation Result:
IV, Source download: Redis-project (jb51.net). rar
The above is the entire content of this article, I hope to help you learn.