Spring 整合 SpringDataRedis

女爷i 2022-12-13 04:34 256阅读 0赞

1.1 相关依赖

  1. <!-- jedis 2.9.0 会报 ClassNotFoundException: redis.clients.jedis.util.Pool -->
  2. <dependency>
  3. <groupId>redis.clients</groupId>
  4. <artifactId>jedis</artifactId>
  5. <version>3.0.0</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework.data</groupId>
  9. <artifactId>spring-data-redis</artifactId>
  10. <version>2.3.4.RELEASE</version>
  11. </dependency>

1.2 配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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" xsi:schemaLocation="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">
  3. <!-- 加载配置信息 -->
  4. <context:property-placeholder location="classpath:*.properties" />
  5. <!-- redis 参数(不配置为默认) -->
  6. <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
  7. <property name="maxIdle" value="${redis.maxIdle}" />
  8. <property name="maxWaitMillis" value="${redis.maxWait}" />
  9. <property name="testOnBorrow" value="${redis.testOnBorrow}" />
  10. </bean>
  11. <!-- redis 地址配置,无密码可以省略 -->
  12. <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"/>
  13. <!-- redisTemplate 配置 -->
  14. <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
  15. <property name="connectionFactory" ref="JedisConnectionFactory" />
  16. </bean>
  17. </beans>

1.3 示例

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/10/10 * @description Spring 整合 Spring Data Redis */
  2. @SpringJUnitConfig(locations = "classpath:redis.xml")
  3. public class RedisTest {
  4. @Autowired
  5. private RedisTemplate<String, Object> redisTemplate;
  6. @Test
  7. public void redis() {
  8. redisTemplate.opsForValue().set("name", "张三");
  9. Object name = redisTemplate.opsForValue().get("name");
  10. System.out.println(name);
  11. }
  12. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,256人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringDataRedis介绍

      实际项目中我们一般都会使用Redis来作为我们的缓存组件,往往又会和Spring一块使用,虽然Redis官方提供的有Jedis等客户端工具,但是使用的时候还是有些不方便,这