redis与spring 集成(单机)

最近在研究redis与spring集成,就写一下集成的过程吧。

看网上大部分人都是配置RedisTemplate然后自己实现Cache接口里面的方法,但是spring-data-redis包里面有写好的RedisCache类,因此下面配置就是使用spring-data-redis包里面的类来操作redis,目前是可以使用的,不知道有什么问题没有。

项目使用maven,因此先在pom.xml 中引入jar包:

        
            org.springframework.data
            spring-data-redis
            2.0.2.RELEASE
        
        
            redis.clients
            jedis
            2.9.0
        

配置spring-redis.xml:
1.配置spring读取配置文件redis-config.properties



        
            
                classpath:config/redis-config.properties
            
        
 

2.redis-config.properties中配置redis 连接的host,port等信息:

redis.host=localhost
redis.port=6379
redis.password=
redis.maxIdle=8
redis.maxWait=6000
redis.testOnBorrow=true

3.在spring-redis.xml中配置连接信息:


    
        
        
        
    


    

p:pool-config-ref="poolConfig" 配置poolConfig为上面定义的poolConfig
p:usePool="true" 配置使用连接池,这个默认是true,不配置也可以。

4.初始化操作redis的类

   
    
        
    

5.使用默认的配置

  
    

默认的配置会初始化一个永不过期,使用StringRedisSerializer序列化key,使用JdkSerializationRedisSerializer序列化value的配置。

6.配置redisCache

    
    
        
        
        
    

其中name 对应的是当前这个cache的名字
7.接下来就是配置spring的注解了

   
          
            
                
            
        
    

8.最后在spring的主配置文件中开启注解:

 

9.以上配置完成后就可以在代码中使用spring的注解了

@Cacheable(value = "default" ,key = "'mp-['+#userId+']'",sync = false)

sync 这个属性如果设置为true的话,就是同步加载,避免cache中没有值时多个线程同时请求到数据库。

你可能感兴趣的:(redis与spring 集成(单机))