Use Redis as the cache for the web System. Integrate Redis with Spring's Cache. I. Writing about the relevant XML file for Redis <?xml version=
"1.0"encoding=
"UTF-8"? ><beans xmlns=
"http://www.springframework.org/schema/beans"Xmlns:cache=
"http://www.springframework.org/schema/cache"Xmlns:c=
"http://www.springframework.org/schema/c"Xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"xmlns:p=
"http://www.springframework.org/schema/p"xsi:schemalocation=
"
Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
Http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd " ><!--turn on cache annotations--<cache:annotation-driven/> <!--jedis Client connection Factory--><bean id=
"jedisconnectionfactory"class=
"org.springframework.data.redis.connection.jedis.JedisConnectionFactory"P:host-name=
"192.168.1.200"p:port=
"6379"/> <!--redistemplate Templates-<bean id=
"redistemplate" class=
"org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref=
"jedisconnectionfactory"/><!--redis Cache Manager-<bean id=
"cachemanager" class=
"org.springframework.data.redis.cache.RedisCacheManager" c:template-ref=
"redistemplate"/>
</beans> entity class
public class Student implements serializable{/** * */
Private
Static
Final
Long
Serialversionuid= -4676194082313592019l;
PrivateInteger id;
PrivateString name;
PrivateInteger age;
publicInteger getId () {
returnId }
public
voidSetId (Integer Id) {
this. id = id; }
publicString GetName () {
returnName }
public
voidSetName (String Name) {
this. Name = name; }
publicInteger getage () {
returnAge }
public
voidSetage (Integer Age) {
this. Age = age; } @Override
publicString toString () {
return"Student [id=" + ID + ", name=" + name + ", age=" + age + "]"; }} third, Data Access Layer
public interface Studentmapper {@Insert ("Insert into student (id,name,age) values (#{id},#{name},#{age})")
public
voidInsert (Student Student); @Delete ("Delete from student where id = #{id}")
public
voidDelete (@Param ("id") Integer id); @Update ("Update student set name=#{name},age=#{age} where Id=#{id}")
public
voidUpdate (Student Student); @Select ("select * from student where Id=#{id}")
publicStudent Querybyid (@Param ("id") Integer id); } iv. Business Processing layer (key)
public interface Istudentservice {
public
voidAdd (Student Student);
public
voidDelete (Integer id);
public
voidUpdate (Student Student);
publicStudent Querybyid (Integer id); }
public class Studentserviceimpl extends Baseservice implements istudentservice{
PrivateStudentmapper mapper; @CachePut (key= "#student. id", value= "student") @Override
public
voidAdd (Student Student) {mapper = Writablesqlsession.getmapper (studentmapper.
class); Mapper.insert (student); } @Override
public
voidDelete (Integer Id) {mapper = Writablesqlsession.getmapper (studentmapper.
class); Mapper.delete (id); } @Override
public
voidUpdate (Student Student) {mapper = Writablesqlsession.getmapper (studentmapper.
class); Mapper.update (student); } @Cacheable (key= "#id", value= "student") @Override
publicStudent Querybyid (Integer id) {mapper = Readonlysqlsession.getmapper (studentmapper.
class);
returnMapper.querybyid (id); }} the most important three annotations are @cacheable () and @cacheevict () and @cacheput () for cache declarations, The cache abstraction class provides two Java annotations: @Cacheable and @cacheevict, These two annotations allow methods to trigger caching or cache Extraction. @Cacheable caching is applied to methods that read data, such as lookup methods, that can be cached. Just like the meaning of the annotation name, @Cacheable used to differentiate a cacheable method, which means that the result of the Method's run is loaded into the cached method, so that in the subsequent method call, the cached value is returned, and this method is not actually executed. The simplest composition, the annotation declaration requires a cache name that is related to the cached method:
@Cacheable ("books")Public book findbook (ISBN isbn) {...}In the above fragment, the Findbook method is related to the cache with the name Books. Each time the method is called, the cache is checked to see if the call has been executed and has not been duplicated. In most cases, only one cache is declared, and annotations allow multiple names to be specified so that a cache is not known to be in Use. In this case, each cache will be checked before executing the method, and if at least one cache is selected, the associated value will be returned: (note: all other caches that do not contain this method will be updated, even if the cached method is not actually executed)
@Cacheable ({"books", "isbns"})Public book findbook (ISBN isbn) {...}The generation of the default key because the cache is actually a key-value pair storage, a cached method each time the call needs to be converted into an appropriate key in order to access the Cache. Outside of this box, the cache abstract class uses a simple Keygenerator (key generator) based on the following algorithm: 1. If no arguments are given, the simplekey.empty is Returned. 2. If only one parameter is given, return that instance. 3. If more than one parameter is specified, returns a simplekey containing all Parameters. This processing is perfect for most use cases as long as the parameter has natural keys and implements the valid Hashcode () and equals () methods, and if this does not conform to this scenario, the key generation strategy needs to be changed. Provides a different default key generator that requires implementation of the Org.springframework.cache.KeyGenerator Interface. Once configured, this generator will be used for each declaration that does not specifically specify its own key generation Strategy. user-defined key Generator declaration because the cache is a generic class, it is much like a target method that has many signatures that cannot be easily mapped at the top of the cache Structure. This becomes apparent when the target method has more than one parameter that is appropriate for the Cache. For example:
@Cacheable ("books")Public book Findbook (ISBN isbn, boolean checkwarehouse, boolean includeused) At first glance, the two Boolean parameters affect the way books are found, and they are useless for caching. For this scenario, @Cacheable annotations allow the user to specify the key generation strategy through the key Property. Development and can use Spel to get parameters (or the attributes they contain), and execute them in a way that does not even write any code or implement any excuses to invoke different methods. This is a recommended method outside of the default Generator. @CachePut applied to the method of writing data, such as the New/modified method @cacheevict is applied to the method of removing the data, such as the SPEL context data provided by the Delete method
Spring Cache provides some spel contextual data for our use, and the following table is directly from the spring official documentation:
Name |
Position |
Describe |
Example |
MethodName |
Root Object |
The name of the method that is currently being called |
#root.methodName
|
Method |
Root Object |
The method that is currently being called |
#root.method.name
|
Target |
Root Object |
The target object that is currently being called |
#root.target
|
Targetclass |
Root Object |
The target object class that is currently being called |
#root.targetClass
|
Args |
Root Object |
The parameter list of the currently called method |
#root.args[0]
|
Caches |
Root Object |
The list of caches used by the current method call (such as @cacheable (value={"cache1", "cache2"}), Then there are two cache |
#root.caches[0].name
|
Argument Name |
Execution context |
Parameters of the currently called method, such as FindByID (Long id), We can get the parameters by #id |
#user. ID |
Result |
Execution context |
The return value after the method executes (only if the judgment is valid after the method executes, such as ' unless ', ' cache evict ' Beforeinvocation=false) |
#result
|
Conditional caching sometimes, A method does not always apply to Caching. Cached annotations are evaluated by the conditional parameter with the SPEL expression to be true or false to achieve this Function. If True is returned, then this method is cached, and if not, the method is not Cached. As an example, the following method will be cached only if the parameter name is less than 32 in Length:
@Cacheable (value= "book", condition= "#name. length <")Public book Findbook (String Name)This blog post is reproduced from http://blog.csdn.net/qinsihang/article/details/22722253
Spring integrates Redis as a cache