RedisTemplate应用

本文介绍了如何在项目中应用RedisTemplate,从工程目录结构到启动Redis,再到配置文件如applicationContext.xml、redis.properties和spring-redis.xml的设置。接着讨论了Maven依赖和web.xml配置,以及涉及的Java代码,包括TestAction、ApplicationContextAwareListner、manager和dao层的实现。最后,文章包含了测试部分,展示如何验证RedisTemplate的正确集成和使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RedisTemplate应用

工程目录

在这里插入图片描述

启动redis

Redis学习Ⅰ

配置文件

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">


    <!-- 初始化bean,为了实现初始化时启动操作 -->
    <bean id="applicationContextAwareListner"
          class="com.yaoyan.listener.ApplicationContextAwareListner"></bean>
</beans>

redis.properties

IntelliJIDEA无法识别properties文件解决

redis.pool.maxTotal=1000
redis.pool.maxIdle=300
redis.pool.maxWaitMillis=3000


redis.hostname=127.0.0.1
redis.port=6379
redis.password=
redis.dbIndex=1
redis.timeout=2000

spring-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/util
      http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <context:component-scan base-package="com.yaoyan.redis.dao" />

    <context:property-placeholder
            location="classpath:conf/redis.properties" />


    <!-- Jedis 连接池配置 -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.pool.maxTotal}" />
        <property name="maxIdle" value="${redis.pool.maxIdle}" />
        <property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
    </bean>


    <!-- Jedis ConnectionFactory 数据库连接配置 -->
    <bean id="jedisConnectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.hostname}" />
        <property name="port" value="${redis.port}" />
        <property name="password" value="${redis.password}" />
        <property name="database" value="${redis.dbIndex}" />
        <property name="timeout" value="${redis.timeout}" />
        <property name="poolConfig" ref="jedisPoolConfig" />


    </bean>

    <bean id="redisScript"
          class="org.springframework.data.redis.core.script.DefaultRedisScript">
        <property name="location" value="classpath:redisscripts/hashcheckandset.lua" />
        <property name="resultType" value="java.lang.Boolean" />
    </bean>


    <!-- redisTemplate配置,redisTemplate是对Jedis的对redis操作的扩展,有更多的操作,封装使操作更便捷 -->
    <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"></property>
    </bean>

    <!-- redisTemplate配置,redisTemplate是对Jedis的对redis操作的扩展,有更多的操作,封装使操作更便捷 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"></property>
        <property name="keySerializer">
            <bean
                    class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
        </property>
        <property name="hashKeySerializer">
            <bean
                    class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean
                    class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
        </property>
        <property name="hashValueSerializer">
            <bean
                    class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
        </property>
    </bean>

</beans>

maven

<?xml version="1.0" encoding="UTF-8"?>

<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.yaoyan</groupId>
  <artifactId>maven</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>maven Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>3.0-alpha-1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- jackson start -->

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.1.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.1.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.1.0</version>
    </dependency>
    <!-- Jersey -->
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-server</artifactId>
      <version>1.8</version>
    </dependency>

    <dependency>
      <groupId>com.owlike</groupId>
      <artifactId>genson</artifactId>
      <version>1.4</version>
    </dependency>

    <!-- Spring 3 dependencies -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>

    <!-- Jersey + Spring -->
    <dependency>
      <groupId>com.sun.jersey.contribs</groupId>
      <artifactId>jersey-spring</artifactId>
      <version>1.8</version>
      <exclusions>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
        </exclusion>
      </exclusions>
    </dependency>


    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.7.3</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>1.6.0.RELEASE</version>
    </dependency>

  </dependencies>

  <profiles>
    <profile>
      <id>test</id>
      <properties>
        <resource.path>src/profiles/test</resource.path>
      </properties>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
    </profile>
  </profiles>

  <build>
    <finalName>maven</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>

    <resources>
      <resource>
        <directory>src/profiles/test</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
          <include>**/*.tld</include>
        </includes>
        <filtering>false</filtering>
      </resource>

    </resources>
  </build>
</project>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>


  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:conf/applicationContext.xml;
      classpath:conf/spring-redis.xml;
    </param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>


  <servlet>
    <servlet-name>jersey-serlvet</servlet-name>
    <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>com.yaoyan.action</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>jersey-serlvet</servlet-name>
    <url-pattern>/api/*</url-pattern>
  </servlet-mapping>


</web-app>

java代码

TestAction

package com.yaoyan.action;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Component;

import com.yaoyan.manager.TestEntityManager;

@Component
@Path("/demo")
public class TestAction {

    @GET
    @Path("/hello")
    public Response sayHello(@QueryParam("name") String name) {
        TestEntityManager testEntityManager = new TestEntityManager();
        testEntityManager.setTest("redis");
        return Response.status(200).entity(testEntityManager.getTest()).build();
    }
}

ApplicationContextAwareListner

package com.yaoyan.listener;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextAwareListner implements ApplicationContextAware {

    private static ApplicationContext context;

    public static ApplicationContext getContext() {
        return context;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextAwareListner.context = applicationContext;
    }
}

manager

package com.yaoyan.manager;

import com.yaoyan.listener.ApplicationContextAwareListner;
import com.yaoyan.redis.dao.TestEntityDao;

public class TestEntityManager {

     TestEntityDao testEntityDao = ApplicationContextAwareListner.getContext().getBean(TestEntityDao.class);

     public void setTest(String str) {
        testEntityDao.put(str);
    }

    public String getTest() {
        return testEntityDao.get();
    }
}

dao

package com.yaoyan.redis.dao;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class TestEntityDao {
    private static Log logger = LogFactory.getLog(TestEntityDao.class);

    private final static String KEYNAME = "TestEntityDao";

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public void put(String str) {
        stringRedisTemplate.boundValueOps(KEYNAME).set(str);
    }

    public String get() {
        String str = stringRedisTemplate.boundValueOps(KEYNAME).get();
        return str;
    }

}

测试

在这里插入图片描述

### 正确配置和使用 Spring Data Redis 中的 `RedisTemplate` 进行缓存操作 #### 配置 Maven 依赖 为了在项目中集成 Spring Data Redis 并利用其功能,需先引入必要的 Maven 依赖项。这可以通过添加如下所示的依赖来完成[^4]: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` #### 自定义序列化方式 默认情况下,`RedisTemplate` 使用 JdkSerializationRedisSerializer 对象来进行数据序列化处理[^3]。然而,在实际应用场景中可能更倾向于采用其他类型的序列化策略(如 JSON 或 String),以便于提高可读性和兼容性。 对于字符串键值对而言,推荐设置为 `StringRedisSerializer`;而对于对象,则可以根据需求选用合适的序列化工具包,比如 Jackson 或者 FastJSON 等第三方库。 下面是一个自定义序列化的例子: ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); // 设置 key 的序列化方式 template.setKeySerializer(new StringRedisSerializer()); // 设置 value 的序列化方式 Jackson2JsonRedisSerializer<Object> jacksonSer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSer.setObjectMapper(om); template.setValueSerializer(jacksonSer); template.afterPropertiesSet(); return template; } } ``` #### 缓存管理与注解支持 除了直接调用 `RedisTemplate` 方法外,还可以借助 Spring Cache 抽象层简化缓存逻辑。通过声明式的编程风格,仅需几个简单的注解就能轻松实现复杂的业务场景下的缓存控制[^5]。 例如,要使某服务的方法结果被自动保存到 Redis 缓存里,并且每次请求相同参数时优先从缓存获取而不是重新计算,可以在该方法上面加上 `@Cacheable` 注解并指定对应的 cache name 属性即可。 另外还有诸如 `@CachePut`, `@CacheEvict` 等用于更新/移除特定条目的高级特性可供选择。 示例代码片段展示了一个带有基本缓存机制的服务接口定义: ```java @Service public class MyService { private final Logger logger = LoggerFactory.getLogger(MyService.class); @Autowired private RedisTemplate<String, Object> redisTemplate; /** * 获取用户信息. */ @Cacheable(value="users", unless="#result == null") public User getUserById(Long id){ logger.info("Fetching user with ID {}",id); // Simulate database call time by sleeping for a second... try {Thread.sleep(1000);} catch (InterruptedException e){} return new User(id,"John Doe"); } /** * 更新用户信息并将新版本写回缓存. */ @CachePut(value="users", key="#user.id") public User updateUser(User user){ logger.info("Updating user info."); // Update logic here ... return user; } /** * 清理单个用户的缓存记录. */ @CacheEvict(value="users", key="#userId") public void evictUserFromCache(Long userId){ logger.info("Removing cached entry for user {}.",userId); } /** * 批量清理所有用户的缓存记录. */ @CacheEvict(value="users", allEntries=true) public void clearAllUsers(){ logger.info("Clearing entire users' cache..."); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值