欢迎投稿

今日深度:

Spring boot下配置使用redis--注解形式,springredis--

Spring boot下配置使用redis--注解形式,springredis--


继上一篇的template编码方式使用redis
编码形式配置(一)
编码形式使用(二)

经过深入学习发现注解形式的更好用一些,省去一些繁琐的代码,使得你代码看起来更优雅
安装redis服务端请看编码形式配置(一)

1. pom.xml

添加jar包支持,使用springboot自带的redis启动器

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

2. Redis配置文件

这里新加入了缓存管理器,来管理redis.
Spring 3.1 引入了基于注释(annotation)的缓存(cache)技术,它不是一个具体的缓存实现方案(例如EHCache 或者 OSCache、Redis等),而是一个对缓存使用的抽象,通过在既有代码中添加少量它定义的各种 annotation,即能够达到缓存方法的返回对象的效果。
RedisConfig.java


import java.io.Serializable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
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.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.reflect.Method;

@Slf4j
@Configuration
@EnableCaching//启用缓存,这个注解很重要;
//继承CachingConfigurerSupport,为了自定义生成KEY的策略。可以不继承。
public class RedisConfig extends CachingConfigurerSupport{

//因为生产环境和开发环境使用不同的启动资源文件,所以使用了@Profile,用来指定使用的启动资源文件
    @Configuration
    @Profile(value={"dev"})//如果你不需要的话可以删掉
    static class LocalConfiguration {
        //从application.properties中获得以下参数
        @Value("${redis.host}")
        private String host;
        @Value("${redis.port}")
        private Integer port;
        @Value("${redis.password}")
        private String password;

        /**
         * 缓存管理器.
         * @param redisTemplate
         * @return
         */
        @Bean
        public CacheManager cacheManager(RedisTemplate<?,?> redisTemplate) {
           CacheManager cacheManager = new RedisCacheManager(redisTemplate);
           return cacheManager;
        }
        @Bean
        public RedisTemplate<Serializable, Serializable> redisTemplate(
                JedisConnectionFactory redisConnectionFactory) {
            log.info("------------------------------------------");
            log.info("-----------------local redis--------------");
            log.info("------------------------------------------");
            RedisTemplate<Serializable, Serializable> redisTemplate = new RedisTemplate<Serializable, Serializable>();
            //key序列化方式;(不然会出现乱码;),但是如果方法上有Long等非String类型的话,会报类型转换错误;
            //所以在没有自己定义key生成策略的时候,以下这个代码建议不要这么写,可以不配置或者自己实现 ObjectRedisSerializer
            //或者JdkSerializationRedisSerializer序列化方式;
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setHashKeySerializer(new StringRedisSerializer());
            redisTemplate
                    .setValueSerializer(new JdkSerializationRedisSerializer());
            redisTemplate
                    .setHashValueSerializer(new JdkSerializationRedisSerializer());
            //以上4条配置可以不用
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            return redisTemplate;
        }

        @Bean
        public JedisConnectionFactory redisConnectionFactory() {
            JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
            redisConnectionFactory.setHostName(host);
            redisConnectionFactory.setPort(port);
            redisConnectionFactory.setPassword(password);

            return redisConnectionFactory;
        }
    }

    /**
     * 自定义key.
     * 此方法将会根据类名+方法名+所有参数的值生成唯一的一个key
     */
    @Override
    public KeyGenerator keyGenerator() {
        log.info("RedisCacheConfig.keyGenerator()");
       return new KeyGenerator() {
           @Override
           public Object generate(Object o, Method method, Object... objects)           
              StringBuilder sb = new StringBuilder();
              sb.append(o.getClass().getName());
              sb.append(method.getName());
              for (Object obj : objects) {
                  sb.append(obj.toString());
              }
              log.info("keyGenerator=" + sb.toString());
              return sb.toString();
           }
       };
    }
}

@Profile(value={“dev”})代表开发环境用的配置
@Slf4j 是lombok中的注解,不用的可以删掉

3. 使用事例


import java.io.Serializable;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
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.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;

@Slf4j
@Transactional
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserDao userDao;

    // 因为配置文件继承了CachingConfigurerSupport,所以没有指定key的话就是用默认KEY生成策略生成,我们这里指定了KEY
    @Cacheable(value = "userInfo", key = "'findUser' + #id", condition = "#id%2==0")
    // value属性指定Cache名称
    // 使用key属性自定义key
    // condition属性指定发生的条件(如上示例表示只有当user的id为偶数时才会进行缓存)
    @Override
    public UserDto findProperty(String id) {
        UserDto user = userDao.findUser(id);
        return user;
    }

    /**
     * 
     * @CachePut也可以声明一个方法支持缓存功能。 
     * 与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,
     * 而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
     *
     */
    @CachePut("users")
    // 每次都会执行方法,并将结果存入指定的缓存中
    @Override
    public List<UserDto> mybatisQueryAll() {
        return userDao.selectAll();
    }

    @Override
    // @CacheEvict(value="propertyInfo",allEntries=true) 清空全部
    // 删除指定缓存
    @CacheEvict(value = "propertyInfo", key = "'findUser' + #id")
    // 其他属性
    // allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。当指定了allEntries为true时,Spring Cache将忽略指定的key。
    // 清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作。
    // 使用beforeInvocation可以改变触发清除操作的时间,当我们指定该属性值为true时,Spring会在调用该方法之前清除缓存中的指定元素。
    public String cacheEvict(String id) {
        log.info("删除缓存" + id);
        return null;
    }

    /**
     * @Caching注解可以让我们在一个方法或者类上同时指定多个Spring Cache相关的注解。
     * 其拥有三个属性:cacheable、put和evict,分别用于指定@Cacheable、@CachePut和@CacheEvict。
     */
    @Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"),
    @CacheEvict(value = "cache3", allEntries = true) })
    public UserDto find(Integer id) {
        return null;
    }
}

注解详细说明请参考注解说明
是不是感觉注解的形式代码很优雅
有任何问题,请留言^^

   
2
0
查看评论

www.htsjk.Com true http://www.htsjk.com/shujukunews/10055.html NewsArticle Spring boot下配置使用redis--注解形式,springredis-- 继上一篇的template编码方式使用redis 编码形式配置(一) 编码形式使用(二) 经过深入学习发现注解形式的更好用一些,省去一些繁琐的...
评论暂时关闭