Spring 整合 SpringDataRedis

时间:2022-07-27
本文章向大家介绍Spring 整合 SpringDataRedis,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.1 相关依赖

<!-- jedis 2.9.0 会报 ClassNotFoundException: redis.clients.jedis.util.Pool -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-redis</artifactId>
	<version>2.3.4.RELEASE</version>
</dependency>

1.2 配置文件

<?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"
       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">

    <!-- 加载配置信息 -->
    <context:property-placeholder location="classpath:*.properties" />

    <!-- 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>

    <!-- redis 地址配置,无密码可以省略 -->
    <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"/>

    <!-- redisTemplate 配置 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="JedisConnectionFactory" />
    </bean>

</beans>

1.3 示例

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/10
 * @description Spring 整合 Spring Data Redis
 */
@SpringJUnitConfig(locations = "classpath:redis.xml")
public class RedisTest {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    public void redis() {
        redisTemplate.opsForValue().set("name", "张三");
        Object name = redisTemplate.opsForValue().get("name");
        System.out.println(name);
    }
}