Spring Boot和Redis应用

2016-10-17  本文已影响0人  183207efd207

1.导入jar包依赖

  <dependency>     
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-redis</artifactId>
   </dependency>

2.相应的配置

# REDIS (RedisProperties)
#spring.redis.database=
spring.redis.host=
spring.redis.password=
spring.redis.port=6379 
spring.redis.pool.max-idle=100 
spring.redis.pool.min-idle=1
spring.redis.pool.max-active=1000
spring.redis.pool.max-wait=-1
server.port=8081

3.编写cache管理类

package com.example;
import java.lang.reflect.Method;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
    /**
     * 缓存管理(注解用)
     * @author Administrator
     *
     */
    @Configuration
    @EnableCaching
    public class CacheService extends CachingConfigurerSupport {
            
        /**
     * 生成key的策略
     *
     * @return
     */
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
    
    /**
     * 管理缓存
     *
     * @param redisTemplate
     * @return
     */
    @SuppressWarnings("rawtypes")
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //设置缓存过期时间
        // rcm.setDefaultExpiration(60);//秒
        //设置value的过期时间
        Map<String,Long> map=new HashMap();
        map.put("test",60L);
        rcm.setExpires(map);
        return rcm;
    }
    
    /**
     * RedisTemplate配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

4.常用的操作redis的方法

package com.example;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
/**
 * redicache 工具类
 * 
 */
@SuppressWarnings("unchecked")
@Component
public class RedisUtil {
@SuppressWarnings("rawtypes")
@Autowired
private RedisTemplate redisTemplate;
/**
 * 批量删除对应的value
 * 
 * @param keys
 */
public void remove(final String... keys) {
    for (String key : keys) {
        remove(key);
    }
}
/**
 * 批量删除key
 * 
 * @param pattern
 */
public void removePattern(final String pattern) {
    Set<Serializable> keys = redisTemplate.keys(pattern);
    if (keys.size() > 0)
    redisTemplate.delete(keys);
}
/**
 * 删除对应的value
 * 
 * @param key
 */
public void remove(final String key) {
    if (exists(key)) {
        redisTemplate.delete(key);
    }
}
/**
 * 判断缓存中是否有对应的value
 * 
 * @param key
 * @return
 */
public boolean exists(final String key) {
    return redisTemplate.hasKey(key);
}
/**
 * 读取缓存
 * 
 * @param key
 * @return
 */
public Object get(final String key) {
    Object result = null;
    ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
    result = operations.get(key);
    return result;
}
/**
 * 写入缓存
 * 
 * @param key
 * @param value
 * @return
 */
public boolean set(final String key, Object value) {
boolean result = false;
try {
    ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
    operations.set(key, value);
    result = true;
} catch (Exception e) {
    e.printStackTrace();
}
    return result;
}
/**
 * 写入缓存
 * 
 * @param key
 * @param value
 * @return
 */
public boolean set(final String key, Object value, Long expireTime) {
    boolean result = false;
    try {
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        operations.set(key, value);
        redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
        result = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
        return result;
    }
}

5.测试

@RequestMapping("/")
@Cacheable(value="test")
public String getSessionId(HttpSession session){
    redisUtil.set("123", "测试");
    System.out.println("进入了方法");
    String string= redisUtil.get("123").toString();
    return string;
}
上一篇下一篇

猜你喜欢

热点阅读