ssm 整合spring-data-redis做缓存

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fantasic_van/article/details/83016336

spring对各种缓存提供了良好的支持,当然redis也不例外。

此处记录使用spring-data-redis做缓存的一个例子。

一、导入的jar包

此处版本是可以与 spring 4.x兼容的

<!-- spring-data-redis -->
<dependency>
    <groupId>org.springframework.data</groupId>
	<artifactId>spring-data-redis</artifactId>
	<version>1.5.2.RELEASE</version>
</dependency>
		
<!-- java连接redis -->
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.9.0</version>
</dependency>   
		
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.4.2</version>
</dependency>  

二、添加spring-redis.xml配置

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

	<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="hostName" value="127.0.0.1"/>
		<property name="port" value="6379"/>
	</bean>
	
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="redisConnectionFactory"/>
	</bean>
	
	<bean class="org.springframework.data.redis.cache.RedisCacheManager">
		<constructor-arg ref="redisTemplate"></constructor-arg>
		<property name="defaultExpiration" value="300"/>
	</bean>

</beans>

三、使用注解解释

  • 1、@EnableCaching  声明在需要缓存的类上,开启redis缓存
  • 2、@Cacheable(value={...})  声明在需要缓存的方法上,首先应该在缓存中查找方法的返回值。如果这个值能够找到,就会返回存储的值,否则的话,这个方法就会被调用,返回值会放在缓存之中。
  • 3、@CacheCut  表明Spring应该将方法的返回值放到缓存中,在方法的调用前并不会检查缓存,方法始终都会被调用
  • 4、@CacheEvict 表明从Spring中清除一个或多个缓存
  • 5、@Caching 这是一个分组的注解,能够同时应用多个其他的缓存注解

四、使用实例

 截取了部分代码

五、查看redis客户端中

已经多了两个key,命名规则为 设置的value + ~keys

六、测试再次查询,不会出现sql了,说明是直接在缓存中拿到的

猜你喜欢

转载自blog.csdn.net/fantasic_van/article/details/83016336