springboot整合redis和springCache

1 篇文章 0 订阅
1 篇文章 0 订阅

根据上一篇在整合springCache
springboot整合redis

1.在配置文件中添加注解@EnableCaching (RedisConfig.class)


/**
 * Created by zhuzhengping on 2017/2/19.
 * redis配置
 */
@Configuration
@EnableCaching  //这个使用springCache----->如果只用redis,可以不用添加
@PropertySource("classpath:config/redis.properties")
public class RedisConfig2 extends CachingConfigurerSupport {

    @Bean
    @Override
    public KeyGenerator 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());
                }
                System.out.println("keyGenerator=" + sb.toString());
                return sb.toString();
            }
        };
    }


    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate){
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        //配置CacheManneg来配置默认的过期时间和针对每个缓存容器(value)
        redisCacheManager.setDefaultExpiration(60);
        Map<String,Long> expiresMap=new HashMap<>();
        expiresMap.put("Product",5L);
        redisCacheManager.setExpires(expiresMap);

        return redisCacheManager;
    }

    @Autowired
    private Environment env;

    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName(env.getProperty("redis.host").trim());
        jedisConnectionFactory.setPort(Integer.parseInt(env.getProperty("redis.port").trim()));
        jedisConnectionFactory.setPassword(env.getProperty("redis.password").trim());
        jedisConnectionFactory.setDatabase(Integer.parseInt(env.getProperty("redis.database").trim()));
        jedisConnectionFactory.setUsePool(true);
        jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
        return jedisConnectionFactory;
    }
/*
    @Bean
    public RedisTemplate<String,String> redisTemplate(){
        //StringRedisTemplate的构造方法中默认设置了stringSerializer
        RedisTemplate<String,String> redisTemplate = new StringRedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory());

        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);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }*/

    /**
     * 配置RedisTemplate
     * 设置添加序列化器
     * key 使用string序列化器
     * value 使用Json序列化器
     * 还有一种简答的设置方式,改变defaultSerializer对象的实现。
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        //StringRedisTemplate的构造方法中默认设置了stringSerializer
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //set key serializer
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        //set value serializer
        template.setDefaultSerializer(jackson2JsonRedisSerializer);

        template.setConnectionFactory(redisConnectionFactory());
        template.afterPropertiesSet();
        return template;
    }
}

2.通过注解的方式缓存

package com.xpf.services;

import com.xpf.config.RedisBaseDao;
import com.xpf.config.RedisKeyPrefix;
import com.xpf.dao.UserInfoAutoDao;
import com.xpf.domain.UserInfo;
import com.xpf.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
@CacheConfig(cacheNames = "user")
public class UserInfoServices {

    @Autowired
    UserInfoAutoDao userInfoAutoDao;
    @Autowired
    UserInfoMapper userInfoMapper;
    @Resource(name = "redisTemplate")
    protected ValueOperations<String, UserInfo> valueOperations;
    @Autowired
    RedisBaseDao redisBaseDao;
    @Autowired
    RedisTemplate redisTemplate;


    public UserInfo getUser(Long id) {
        String key = RedisKeyPrefix.User + id;
        /**
         *判断redis中是否存在该 缓存
         */
        Boolean hasKey = redisTemplate.hasKey(key);

        if (hasKey) {
            System.out.println("----------redis中取的key----------");
            UserInfo userInfo= valueOperations.get(key);//(UserInfo) redisTemplate.opsForValue().get(key);
            return userInfo;
        }
        UserInfo userInfo=userInfoAutoDao.findUser(id);
        redisTemplate.opsForValue().set(key,userInfo,600, TimeUnit.SECONDS);
        return  userInfo;
    }

    /**
     * 通过整合springCache,实现注解式缓存
     * 通过id查询,如果查询到则进行缓存
     * @param id 实体类id
     * @return 查询到的实现类
     */
    @Cacheable(key = "\"user_\" + #id")
    public UserInfo getUserCache(Long id) {

        UserInfo userInfo=userInfoAutoDao.findUser(id);
        return  userInfo;
    }


    /*
     * 通过id查询,如果查询到则进行缓存,并且设置缓存的有效期
     * 值属性上用#号隔开,第一个是原始的缓存容器名称,第二个是缓存的有效时间,第三个是缓存的自动刷新时间,单位都是秒。
     * @param id 实体类id
     */
    @Cacheable(value = "xpf#10#15",key = "\"user_\" + #id")
    public UserInfo getUserCacheTimeout(Long id) {
        System.out.println("-------------从这里访问数据库-----------");

        UserInfo userInfo=userInfoAutoDao.findUser(id);
        return  userInfo;
    }
    /**
     * 单个user对象的插入操作,使用user+id
     * @param user
     * @return
     */
    @CachePut(key = "\"user_\" + #user.uid")
    public UserInfo saveUser(UserInfo user){
        userInfoMapper.insert(user);
        return user;
    }

    @CacheEvict(key = "\"user_\" + #id")
    public void deleteById(Long id){
        userInfoMapper.deleteByPrimaryKey(id);
    }
}

3.测试

 @Test
    public void testCache() {
        System.out.println("=======第一次调用======");
        System.out.println(services.getUserCache(Long.valueOf(3)).toString());
        System.out.println("===========第二次调用=======");
        System.out.println(services.getUserCache(Long.valueOf(3)).toString());
    }

    @Test
    public void testCacheTimeout() {
        System.out.println("=======第一次调用======");
        System.out.println(services.getUserCacheTimeout(Long.valueOf(3)).toString());
        System.out.println("===========第二次调用=======");
        System.out.println(services.getUserCacheTimeout(Long.valueOf(3)).toString());
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值