您的位置:首页 > 数据库 > Redis

Redis与spring整合缓存的业务场景使用方法一

2017-05-05 10:16 816 查看
需求:给商品的包装做缓存(该需求只为了测试缓存使用)
1、pom.xml(版本已外部定义)



2、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:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"
default-lazy-init="true">
<context:annotation-config/>
<context:property-placeholder ignore-unresolvable="true" location="classpath:config.properties" />
<!-- Redis -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"/>

<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="timeout" value="${redis.timeout}" />
<property name="usePool" value="${redis.usePool}" />
<property name="poolConfig" ref="jedisPoolConfig" />
</bean>

<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >
<property name="connectionFactory" ref="jedisConnectionFactory"/>
</bean>
</beans>



3、Service添加缓存配置





4、测试缓存
发现可以正常使用
5、当修改商品时,包装信息发生变化时,或者直接把当前商品删除(当前业务无删除商品功能)时,应该删除缓存,实现数据同步。

结语:
这个缓存使用方法是比较简单的,也是比较容易理解的缓存使用方式,当然每次使用时都需要做判断是相当麻烦的事,当然spring在整合redis时,也做了改善,给我们省去了很多不必要的操作,下篇分析。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: