spring data redis使用

来源:互联网 发布:李约瑟难题的答案 知乎 编辑:程序博客网 时间:2024/06/04 05:23

maven工程导入坐标

        <!-- redis nosql 内存数据库 -->        <dependency>            <groupId>redis.clients</groupId>            <artifactId>jedis</artifactId>            <version>${jedis.version}</version>        </dependency>        <dependency>            <groupId>org.springframework.data</groupId>            <artifactId>spring-data-redis</artifactId>            <version>1.4.1.RELEASE</version>        </dependency>

applicationContext配置

<!-- jedis 连接池配置 -->     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">          <property name="maxIdle" value="300" />                <property name="maxWaitMillis" value="3000" />          <property name="testOnBorrow" value="true" />      </bean>      <!-- jedis 连接工厂 -->    <bean id="redisConnectionFactory"          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"          p:host-name="localhost" p:port="6379" p:pool-config-ref="poolConfig"          p:database="0" />      <!-- spring data 提供 redis模板  -->    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">          <property name="connectionFactory" ref="redisConnectionFactory" />         <!-- 如果不指定 Serializer   -->        <property name="keySerializer">            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />        </property>        <property name="valueSerializer">            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer">             </bean>        </property>     </bean>  

Spring自动注入RedisTemplate

    @Autowired    private RedisTemplate<String, String> redisTemplate;

将键值对保存到redis,设置保存时间

    redisTemplate.opsForValue().set(key,value, 24,TimeUnit.HOURS);

用key将键值对删除

redisTemplate.delete(key);
原创粉丝点击