search
HomeJavajavaTutorialDetailed explanation of examples of spring integrating redis cache and using it in the form of annotations

This article mainly introduces spring's integration of redis cache and its use in the form of annotations (@Cacheable, @CachePut, @CacheEvict). It has certain reference value. Those who are interested can learn more.

The maven project relies on 2 jar packages in pom.xml, and other spring jar packages are omitted:

<dependency> 
  <groupId>redis.clients</groupId> 
  <artifactId>jedis</artifactId> 
  <version>2.8.1</version> 
</dependency> 
<dependency> 
  <groupId>org.springframework.data</groupId> 
  <artifactId>spring-data-redis</artifactId> 
  <version>1.7.2.RELEASE</version> 
</dependency>

Contents in spring-Redis.xml:

<?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:p="http://www.springframework.org/schema/p"  
  xmlns:context="http://www.springframework.org/schema/context"  
  xmlns:mvc="http://www.springframework.org/schema/mvc"  
  xmlns:cache="http://www.springframework.org/schema/cache" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans   
            http://www.springframework.org/schema/beans/spring-beans-4.2.xsd   
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context-4.2.xsd   
            http://www.springframework.org/schema/mvc   
            http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
            http://www.springframework.org/schema/cache  
            http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">  
   
  <context:property-placeholder location="classpath:redis-config.properties" />  
 
  <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->  
  <cache:annotation-driven cache-manager="cacheManager" />  
   
   <!-- redis 相关配置 -->  
   <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
     <property name="maxIdle" value="${redis.maxIdle}" />   
     <property name="maxWaitMillis" value="${redis.maxWait}" />  
     <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
   </bean>  
 
   <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
    p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>  
  
   <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
     <property name="connectionFactory" ref="JedisConnectionFactory" />  
   </bean>  
   
   <!-- spring自己的缓存管理器,这里定义了缓存位置名称 ,即注解中的value -->  
   <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">  
     <property name="caches">  
      <set>  
        <!-- 这里可以配置多个redis --> 
        <!-- <bean class="com.cn.util.RedisCache">  
           <property name="redisTemplate" ref="redisTemplate" />  
           <property name="name" value="default"/>  
        </bean> -->  
        <bean class="com.cn.util.RedisCache">  
           <property name="redisTemplate" ref="redisTemplate" />  
           <property name="name" value="common"/>  
           <!-- common名称要在类或方法的注解中使用 --> 
        </bean> 
      </set>  
     </property>  
   </bean>  
   
</beans>
## Contents in #redis-config.properties:

# Redis settings 
# server IP 
redis.host=127.0.0.1 
# server port 
redis.port=6379 
# server pass 
redis.pass= 
# use dbIndex 
redis.database=0 
# 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例 
redis.maxIdle=300 
# 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间(毫秒),则直接抛出JedisConnectionException;  
redis.maxWait=3000 
# 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的  
redis.testOnBorrow=true

Contents in com.cn.util.RedisCache class:

package com.cn.util;  
import java.io.ByteArrayInputStream; 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
 
import org.springframework.cache.Cache; 
import org.springframework.cache.support.SimpleValueWrapper; 
import org.springframework.dao.DataAccessException; 
import org.springframework.data.redis.connection.RedisConnection; 
import org.springframework.data.redis.core.RedisCallback; 
import org.springframework.data.redis.core.RedisTemplate; 
 
public class RedisCache implements Cache{ 
 
  private RedisTemplate<String, Object> redisTemplate;  
  private String name;  
  public RedisTemplate<String, Object> getRedisTemplate() { 
    return redisTemplate;  
  } 
    
  public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) { 
    this.redisTemplate = redisTemplate;  
  } 
    
  public void setName(String name) { 
    this.name = name;  
  } 
    
  @Override  
  public String getName() { 
    // TODO Auto-generated method stub  
    return this.name;  
  } 
 
  @Override  
  public Object getNativeCache() { 
   // TODO Auto-generated method stub  
    return this.redisTemplate;  
  } 
  
  @Override  
  public ValueWrapper get(Object key) { 
   // TODO Auto-generated method stub 
   System.out.println("get key"); 
   final String keyf = key.toString(); 
   Object object = null; 
   object = redisTemplate.execute(new RedisCallback<Object>() { 
   public Object doInRedis(RedisConnection connection)  
         throws DataAccessException { 
     byte[] key = keyf.getBytes(); 
     byte[] value = connection.get(key); 
     if (value == null) { 
       return null; 
      } 
     return toObject(value); 
     } 
    }); 
    return (object != null ? new SimpleValueWrapper(object) : null); 
   } 
  
   @Override  
   public void put(Object key, Object value) { 
    // TODO Auto-generated method stub 
    System.out.println("put key"); 
    final String keyf = key.toString();  
    final Object valuef = value;  
    final long liveTime = 86400;  
    redisTemplate.execute(new RedisCallback<Long>() {  
      public Long doInRedis(RedisConnection connection)  
          throws DataAccessException {  
        byte[] keyb = keyf.getBytes();  
        byte[] valueb = toByteArray(valuef);  
        connection.set(keyb, valueb);  
        if (liveTime > 0) {  
          connection.expire(keyb, liveTime);  
         }  
        return 1L;  
       }  
     });  
   } 
 
   private byte[] toByteArray(Object obj) {  
     byte[] bytes = null;  
     ByteArrayOutputStream bos = new ByteArrayOutputStream();  
     try {  
      ObjectOutputStream oos = new ObjectOutputStream(bos);  
      oos.writeObject(obj);  
      oos.flush();  
      bytes = bos.toByteArray();  
      oos.close();  
      bos.close();  
     }catch (IOException ex) {  
        ex.printStackTrace();  
     }  
     return bytes;  
    }  
 
    private Object toObject(byte[] bytes) { 
     Object obj = null;  
      try { 
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);  
        ObjectInputStream ois = new ObjectInputStream(bis);  
        obj = ois.readObject();  
        ois.close();  
        bis.close();  
      } catch (IOException ex) {  
        ex.printStackTrace();  
      } catch (ClassNotFoundException ex) {  
        ex.printStackTrace();  
      }  
      return obj;  
    } 
  
    @Override  
    public void evict(Object key) {  
     // TODO Auto-generated method stub  
     System.out.println("del key"); 
     final String keyf = key.toString();  
     redisTemplate.execute(new RedisCallback<Long>() {  
     public Long doInRedis(RedisConnection connection)  
          throws DataAccessException {  
       return connection.del(keyf.getBytes());  
      }  
     });  
    } 
  
    @Override  
    public void clear() {  
      // TODO Auto-generated method stub  
      System.out.println("clear key"); 
      redisTemplate.execute(new RedisCallback<String>() {  
        public String doInRedis(RedisConnection connection)  
            throws DataAccessException {  
         connection.flushDb();  
          return "ok";  
        }  
      });  
    } 
 
    @Override 
    public <T> T get(Object key, Class<T> type) { 
      // TODO Auto-generated method stub 
      return null; 
    } 
   
    @Override 
    public ValueWrapper putIfAbsent(Object key, Object value) { 
      // TODO Auto-generated method stub 
      return null; 
    } 
 
}

At this step, most people will want to add the content in web.xml Spring-redis.xml has been added to the startup configuration file (context-param). Let this configuration file be loaded when the project starts. However, the annotations will not take effect after startup.


The correct approach is: configure the servlet controller in web.xml:

<servlet> 
 <servlet-name>SpringMVC</servlet-name> 
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
 <init-param> 
  <param-name>contextConfigLocation</param-name> 
  <param-value>/WEB-INF/spring-mvc.xml</param-value> 
 </init-param> 
 <load-on-startup>1</load-on-startup> 
 <async-supported>true</async-supported> 
</servlet>

During the initialization process of DispatcherServlet, the framework will be in the WEB-INF folder of the web application Look for the configuration file named spring-mvc.xml. If not specified, the default is applicationContext.xml


You only need to introduce the spring-redis configuration file in the spring-mvc.xml file. As the enabling annotation in spring-redis.xml says: the annotation must be declared in the spring main configuration file to take effect.


spring-mvc.xml content, omitting the part that integrates spring with spring MVC:

<?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:p="http://www.springframework.org/schema/p"  
  xmlns:context="http://www.springframework.org/schema/context"  
  xmlns:mvc="http://www.springframework.org/schema/mvc"  
  xsi:schemaLocation="http://www.springframework.org/schema/beans   
            http://www.springframework.org/schema/beans/spring-beans-4.2.xsd   
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context-4.2.xsd   
            http://www.springframework.org/schema/mvc   
            http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"> 
  <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->  
  <context:component-scan base-package="com.cn" />  
   
  <!-- 引入同文件夹下的redis属性配置文件 --> 
  <import resource="spring-redis.xml"/> 
   
</beans>

In the service implementation class:

@Service 
public class UserServiceImpl implements UserService{ 
 
  @Autowired 
  private UserBo userBo; 
 
  @Cacheable(value="common",key="&#39;id_&#39;+#id") 
  public User selectByPrimaryKey(Integer id) { 
    return userBo.selectByPrimaryKey(id); 
  } 
   
  @CachePut(value="common",key="#user.getUserName()") 
  public void insertSelective(User user) { 
    userBo.insertSelective(user); 
  } 
 
  @CacheEvict(value="common",key="&#39;id_&#39;+#id") 
  public void deleteByPrimaryKey(Integer id) { 
    userBo.deleteByPrimaryKey(id); 
  } 
}

The above is the detailed content of Detailed explanation of examples of spring integrating redis cache and using it in the form of annotations. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software