• Spring Boot-整合redis(六)


    redis安装

    参考:https://www.cnblogs.com/LQBlog/p/9214517.html

    单机版

    1.添加pom依赖

    <!-- Spring Boot Reids 依赖 -->
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
                <version>1.5.7.RELEASE</version>
            </dependency>
    
            <!--spring2.0集成redis所需common-pool2-->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-pool2</artifactId>
                <version>2.4.2</version>
            </dependency>

    2.application.properties配置redis连接信息

    spring
        redis:
            host: 192.168.65.128
            port: 6379
            timeout: 0
            password: # 密码 没有则不填

    3.添加测试代码

    @Service
    public class AddressServiceImpl extends BaseServiceImpl<Address> implements AddressService {
        @Resource
        AddressMapper addressMapper;
    
        @Autowired
        private RedisTemplate<Object,Object> redisTemplate;
        @Override
        public Address selectByPrimaryKey(Object key) {
            String redisKey=key.toString();
            Address address=(Address) redisTemplate.opsForValue().get(redisKey);
            if(address==null){
                //防止缓存穿透
                synchronized (this) {
                    address = (Address) redisTemplate.opsForValue().get(redisKey);
                    if (address == null) {
                        address = super.selectByPrimaryKey(key);
                        redisTemplate.opsForValue().set(redisKey, address);
                    }
                }
            }else {
                System.out.println("使用缓存了");
            }
            return address;
    
        }
    }

    红色代码是为了防止内存穿透,比如你这个业务方法有10000个人同时访问,如果不加锁。当第一次访问都判断address为空 然后全部去查数据库,正常应该是一个连接查询数据库并设置缓存 后面9999都使用缓存

    通过redis Desktop Manager查看结果

    因默认key 和value都是用jdk自带的序列化方式JdkSerializationRedisSerializer 可以发现可读性很差

    自定义序列化方式

    新增一个redisConfig 配置序列化方式

    @Configuration
    public class RedisConfig {
    
        /**
         * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
         * @param redisConnectionFactory
         * @return
         */
        @Bean
        public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
            RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(redisConnectionFactory);
    
            // 使用Jackson2JsonRedisSerialize 替换默认序列化
            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);
    
            // 设置value的序列化规则和 key的序列化规则
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
            redisTemplate.afterPropertiesSet();
            return redisTemplate;
        }
    }

    再次测试结果

     集群版

    1.application.properties配置

      redis:
        cluster:
          master: myMaster
          nodes: 192.168.65.128:6379,192.168.65.128:6380,192.168.65.128:6381,192.168.65.128:6382,192.168.65.128:6383,192.168.65.128:6384
        timeout: 0

    2.配置jedisCluster

    @Configuration
    public class RedisConfig {
    
        @Value("${spring.redis.cluster.nodes}")
        private String clusterNodes;
        @Value("${spring.redis.timeout}")
        private int timeout;
    
        @Bean
        public JedisCluster getJedisCluster() {
            String[] cNodes = clusterNodes.split(",");
            Set<HostAndPort> nodes = new HashSet<HostAndPort>();
            // 分割出集群节点
            for (String node : cNodes) {
                String[] hp = node.split(":");
                nodes.add(new HostAndPort(hp[0],Integer.parseInt(hp[1])));
            }
    
            // 创建集群对象
    //      JedisCluster jedisCluster = new JedisCluster(nodes,commandTimeout);
            JedisCluster jedisCluster = new JedisCluster(nodes);
            return jedisCluster;
        }
    }

    3.缓存操作 都通过jedisCluster来操作

    package com.liqiang.utils;
    
    import com.fasterxml.jackson.databind.JsonSerializable;
    import org.apache.tomcat.util.buf.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.util.SerializationUtils;
    import redis.clients.jedis.JedisCluster;
    import tk.mybatis.mapper.util.StringUtil;
    
    import java.io.Serializable;
    import java.lang.reflect.ParameterizedType;
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    @Component
    public class RedisUtil {
    
    
        protected int DEFAULT_EXPIRED_TIME_SECONDS_OBJECT = 1296000;
    
        @Autowired
        private JedisCluster jedisCluster;
    
        public boolean putString(String sKey, String sValue, int expiredInSeconds) {
            boolean result = false;
    
            if (StringUtil.isEmpty(sKey)) {
                return result;
            }
    
            if (this.jedisCluster != null) {
                this.jedisCluster.set(sKey, sValue);
                if (expiredInSeconds > 0) {
                    this.jedisCluster.expire(sKey, expiredInSeconds);
                }
    
                result = true;
            }
    
            return result;
        }
    
        public boolean putString(String sKey, String sValue) {
            return putString(sKey, sValue, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);
        }
    
        public String getString(String sKey) {
            String result = null;
            if (StringUtil.isEmpty(sKey)) {
                return result;
            }
    
            if (this.jedisCluster != null) {
                result = this.jedisCluster.get(sKey);
            }
    
            return result;
        }
    
        public boolean putObject(String sKey, Serializable object, int expiredInSeconds) {
            boolean result = false;
    
            if (StringUtil.isEmpty(sKey)) {
                return result;
            }
    
            if (this.jedisCluster != null) {
                byte[] datas = SerializationUtils.serialize(object);
                byte[] arrKey = sKey.getBytes();
    
                this.jedisCluster.set(arrKey, datas);
                if (expiredInSeconds > 0) {
                    this.jedisCluster.expire(arrKey, expiredInSeconds);
                }
    
                result = true;
            }
    
            return result;
        }
    
        public boolean putObject(String sKey, Serializable object) {
            return putObject(sKey, object, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);
        }
    
        public <T> T getObject(String sKey, Class<T> oclass) {
            Object result = null;
            if (StringUtil.isEmpty(sKey)) {
                return null;
            }
    
            System.out.println(sKey);
            if (this.jedisCluster != null) {
                byte[] arrKey = sKey.getBytes();
    
                byte[] datas = this.jedisCluster.get(arrKey);
    
                if ((datas != null) && (datas.length > 0)) {
                    result = SerializationUtils.deserialize(datas);
                }
            }
            System.out.println("dddd");
           System.out.println(result);
            return (T) result;
        }
    
        public boolean putMap(String sKey, Map<String, String> oMap, int expiredInSeconds) {
            boolean result = false;
    
            if ((StringUtil.isEmpty(sKey)) || (oMap == null) || (oMap.size() <= 0)) {
                return result;
            }
    
            if (this.jedisCluster != null) {
                this.jedisCluster.hmset(sKey, oMap);
                if (expiredInSeconds > 0) {
                    this.jedisCluster.expire(sKey, expiredInSeconds);
                }
    
                result = true;
            }
    
            return result;
        }
    
        public boolean putMap(String sKey, Map<String, String> oMap) {
            return putMap(sKey, oMap, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);
        }
    
        public boolean putMap(String sKey, String sField, String sValue, int expiredInSeconds) {
            boolean result = false;
    
            if ((StringUtil.isEmpty(sKey)) || (StringUtil.isEmpty(sField))) {
                return result;
            }
    
            if (this.jedisCluster != null) {
                this.jedisCluster.hset(sKey, sField, sValue);
                if (expiredInSeconds > 0) {
                    this.jedisCluster.expire(sKey, expiredInSeconds);
                }
    
                result = true;
            }
    
            return result;
        }
    
        public boolean putMap(String sKey, String sField, String sValue) {
            return putMap(sKey, sField, sValue, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);
        }
    
        public Map<String, String> getMap(String sKey) {
            Map result = null;
            if (StringUtil.isEmpty(sKey)) {
                return result;
            }
    
            if (this.jedisCluster != null) {
                result = this.jedisCluster.hgetAll(sKey);
            }
    
            return result;
        }
    
        public Map<String, String> getMap(String sKey, String[] fields) {
            Map result = null;
    
            Map mapAll = getMap(sKey);
            if ((mapAll != null) && (mapAll.size() > 0) && (fields != null) && (fields.length > 0)) {
                result = new LinkedHashMap();
                for (String field : fields) {
                    result.put(field, mapAll.get(field));
                }
    
            }
    
            return result;
        }
    
        public boolean existsMapItem(String sKey, String sField) {
            if ((StringUtil.isEmpty(sKey)) || (StringUtil.isEmpty(sField))) {
                return false;
            }
    
            if (this.jedisCluster != null) {
                return this.jedisCluster.hexists(sKey, sField).booleanValue();
            }
    
            return false;
        }
    
        public boolean putMapValueAsObject(String sKey, String sField, Serializable oValue, int expiredInSeconds) {
            boolean result = false;
    
            if ((StringUtil.isEmpty(sKey)) || (StringUtil.isEmpty(sField))) {
                return result;
            }
    
            if (this.jedisCluster != null) {
                byte[] arrKey = sKey.getBytes();
    
                this.jedisCluster.hset(arrKey, sField.getBytes(), SerializationUtils.serialize(oValue));
                if (expiredInSeconds > 0) {
                    this.jedisCluster.expire(arrKey, expiredInSeconds);
                }
    
                result = true;
            }
    
            return result;
        }
    
        public boolean putMapValueAsObject(String sKey, String sField, Serializable oValue) {
            return putMapValueAsObject(sKey, sField, oValue, this.DEFAULT_EXPIRED_TIME_SECONDS_OBJECT);
        }
    
        public <T> T getMapValueAsObject(String sKey, String sField, Class<T> oClass) {
            Object result = null;
    
            if ((StringUtil.isEmpty(sKey)) || (StringUtil.isEmpty(sField))) {
                return null;
            }
    
            if (this.jedisCluster != null) {
                byte[] datas = this.jedisCluster.hget(sKey.getBytes(), sField.getBytes());
                if ((datas != null) && (datas.length > 0)) {
                    Object tmpObject = SerializationUtils.deserialize(datas);
                    result = tmpObject;
                }
            }
    
            return (T) result;
        }
    
        public void remove(String sKey) {
            if (StringUtil.isEmpty(sKey)) {
                return;
            }
    
            if (this.jedisCluster != null)
                this.jedisCluster.del(sKey);
        }
    
    
    }
  • 相关阅读:
    springboot系列六、springboot配置错误页面及全局异常
    一行代码完成 Java的 Excel 读写--easyexcel
    Docker搭建Portainer可视化界面
    使用spring-boot-admin对spring-boot服务进行监控
    SpringBoot集成JWT实现权限认证
    安装Docker
    Java的 Excel 读写--easyexcel
    SpringBoot 配置文件提示功能
    Mysql数据库中获取时间
    javascript-观察者模式
  • 原文地址:https://www.cnblogs.com/LQBlog/p/9242750.html
Copyright © 2020-2023  润新知