• Springboot2.x 集成redis


    pom.xml 添加

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

    yml 配置

    spring: 
      redis:
        #数据库索引
        database: 0
        host: 118.24.11.111
        port: 6379
        password: 123456
        jedis:
          pool:
            #最大连接数
            max-active: 8
            #最大阻塞等待时间(负数表示没限制)
            max-wait: -1
            #最大空闲
            max-idle: 8
            #最小空闲
            min-idle: 0
        #连接超时时间
        timeout: 10000
    RedisTemplate 配置,重写key和value的序列化

    @Configuration
    public class RedisConfig {
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
            // 配置redisTemplate
            RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            RedisSerializer stringSerializer = new StringRedisSerializer();
            redisTemplate.setKeySerializer(stringSerializer); // key序列化
            redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); // value序列化
            redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化
            redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); // Hash value序列化
            redisTemplate.afterPropertiesSet();
            return redisTemplate;
    
        }
    
    }
    public interface RedisService {
    
        void setObj(String key, Object obj, long timeout);
    
        Object getObj(String key);
    
    }
    @Service("redisService")
    public class RedisServiceImpl implements RedisService {
        @Resource
        private RedisTemplate redisTemplate;
        @Override
        public void setObj(final String key, Object obj, long timeout) {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, obj, timeout, TimeUnit.SECONDS);
        }
        @Override
        public Object getObj(final String key) {
            Object o = redisTemplate.opsForValue().get(key);
            return o;
        }
    
    
    }

    调用示例

    @Override
        public User selectByPrimaryKey(Integer id) throws Exception {
            User user1 = (User)redisService.getObj("user" + id);
            if(user1 == null){
                User user = userMapper.selectByPrimaryKey(id);
                redisService.setObj("user" + id, user, 1000*60*2);
                return user;
            }
            return user1;
        }
  • 相关阅读:
    oracle保留小数,例如0.00
    线程池读取List<T>实例
    Linq XML
    C# 反射 表达式树 模糊搜索
    MVC权限模块
    .NET-提取字符串实践总结
    2014,码农梦想,先从态度开始!
    Biztalk开发系列之二. (AS2配置)
    测试2
    Biztalk Http 适配器使用.开发系列(一)
  • 原文地址:https://www.cnblogs.com/c9999/p/10337525.html
Copyright © 2020-2023  润新知