美文网首页Springbootspring cloud
SpringBoot (六) :springboot与redis

SpringBoot (六) :springboot与redis

作者: 阿亮私语 | 来源:发表于2017-08-15 21:46 被阅读446次

    上一篇写了springboot与mongo的整合,那么这次就写一下springboot与redis的结合,这里使用的是redis集群模式(主从),主从环境的搭建,请参考
    redis集群搭建
    搭建完redis集群环境后,开始springboot之旅

    1、redis介绍

    redis的介绍及应用场景参考 redis介绍

    2、项目构建

    我们还是从redis项目构建开始说起,首先还是进入的spring官网,
    从这里开始构建项目,如下图

    11.png
    当然也可以自己添加pom文件,如下
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    

    3、添加配置文件

    application.properties中

    #-----------------------
    # start redis cluster
    jedis.cluster.nodesString= 103.45.12.176:7000,47.88.221.76:7000,103.45.12.176:7001,47.88.221.76:7001,103.45.12.176:7002,47.88.221.76:7002
    jedis.cluster.testWhileIdle=true
    jedis.cluster.connectionTimeout=60
    jedis.cluster.soTimeout=60
    jedis.cluster.maxAttempts=1000
    jedis.cluster.password=12597758
    # end redis cluster config
    #---------------------------------
    
    

    4、jedis配置类的编写

    这里是核心jedisCluster这个bean的创建

    @Configuration
    @ConfigurationProperties(prefix = "jedis.cluster")
    public class JedisClusterConfig {
        private String nodesString;
        private Boolean testWhileIdle;
        private Integer connectionTimeout;
        private Integer soTimeout;
        private Integer maxAttempts;
        private String  password;
        public Boolean getTestWhileIdle() {
            return testWhileIdle;
        }
    
        public void setTestWhileIdle(Boolean testWhileIdle) {
            this.testWhileIdle = testWhileIdle;
        }
    
        public Integer getConnectionTimeout() {
            return connectionTimeout;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public void setConnectionTimeout(Integer connectionTimeout) {
            this.connectionTimeout = connectionTimeout;
        }
    
        public Integer getSoTimeout() {
            return soTimeout;
        }
    
        public void setSoTimeout(Integer soTimeout) {
            this.soTimeout = soTimeout;
        }
    
        public Integer getMaxAttempts() {
            return maxAttempts;
        }
    
        public void setMaxAttempts(Integer maxAttempts) {
            this.maxAttempts = maxAttempts;
        }
    
        public String getNodesString() {
            return nodesString;
        }
    
        public void setNodesString(String nodesString) {
            this.nodesString = nodesString;
        }
    
        @Bean
        public JedisCluster jedisCluster() {
    
            String[] nodes = nodesString.split(",");
            Set<HostAndPort> nodeSet = new HashSet<HostAndPort>(nodes.length);
    
            for (String node : nodes) {
                String[] nodeAttrs = node.trim().split(":");
                HostAndPort hap = new HostAndPort(nodeAttrs[0], Integer.valueOf(nodeAttrs[1]));
                nodeSet.add(hap);
            }
            JedisPoolConfig poolConfig = new JedisPoolConfig();
            // TODO:password and poolconfig
            JedisCluster jc = new JedisCluster(nodeSet, connectionTimeout, soTimeout, maxAttempts,password, poolConfig);
            return jc;
        }
    }
    
    

    5、通用接口的编写

    经过这几篇的博客,可能也发现很多接口的定义,然后由不同的业务类去实现,面向接口的编程也是经历过近期的一个项目才有了比较深的理解,这些都是跟朱哥和军哥学习的,代码编写的规范,对于一个程序员来说,越早养成越好

    public interface NoSqlClient<T> {
        void set(final String key, final T value);
    
        void set(String key, T value, Long expiry);
    
        <T> boolean exist(Class<T> clazz, String key);
    
        T get(final String key, Class<T> clazz);
    
        <T> void delete(String key);
    
        <T> void hashSet(String key, String hashKey, T hashValue);
    
        Object hashGet(String key, String hashKey, Class<?> hashValueClazz);
    }
    
    

    6、接下来是jedis接口的实现

    @Service
    public class JedisClusterClient<T> implements NoSqlClient<T> {
        protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    
        @Autowired
        private JedisCluster jedisCluster;
        public void set(String key, T value){
            logger.info("-------------"+jedisCluster);
            jedisCluster.set(key,JSON.toJSONString(value,true));
        }
    
        @Override
        public void set(String key, T value, Long expiry) {
    
        }
    
        @Override
        public <T1> boolean exist(Class<T1> clazz, String key) {
            checkRedisKey(key);
            return jedisCluster.exists(key);
        }
    
        @Override
        public T get(String key, Class<T> clazz) {
            checkRedisKey(key);
            String value = jedisCluster.get(key);
            return JSON.parseObject(value, clazz);
        }
    
        @Override
        public <T1> void delete(String key) {
            checkRedisKey(key);
            jedisCluster.del(key);
        }
    
        @Override
        public <T1> void hashSet(String key, String hashKey, T1 hashValue) {
            checkRedisKey(key);
            jedisCluster.hset(key, hashKey, JSON.toJSONString(hashValue));
        }
    
        @Override
        public Object hashGet(String key, String hashKey, Class<?> hashValueClazz) {
            return null;
        }
        /**
         * 检查Redis参数
         *
         * @param key
         * @param value
         * @return
         */
        private String checkRedisNoSqlSupport(final String key, final T value) {
            checkRedisKey(key);
            if (value == null)
                throw new RedisException("value is null!");
            String stringValue = null;
            try {
                stringValue = JSON.toJSONString(value,true);
            } catch (JSONException e) {
                throw new RedisException("value toJSONString exception!");
            }
            if (StringUtils.isEmpty(stringValue))
                throw new RedisException("value is null!");
            return stringValue;
        }
    
        /**
         * 检查Redis key,redis key 长度建议不要超过1M,redis支持512M
         * @param key
         */
        private void checkRedisKey(final String key) {
            if (StringUtils.isEmpty(key))
                throw new RedisException("key is null!");
            if (key.length() > 1000000L)
                throw new RedisException("length of key greater than 1M!");
        }
    }
    
    

    这里我只写了几个基础的核心配置,包括一些异常的处理,这里都没有贴出代码,当然代码在文章最后也会给出,不必担心

    7、业务dao的实现

    不同的业务只需继承上面的类即可

    @Component
    public class UserInfoCacheDao extends JedisClusterClient<UserInfo> {
        public void setUserInfo(UserInfo userInfo){
            super.set("lessons.user:1",userInfo);
        }
    }
    

    这里同样也是只写了一个set方法

    8、单元测试

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest
    public class UserInfoCacheDaoTest {
        @Autowired
        private UserInfoCacheDao userInfoCacheDao;
        @Test
        public void setUserInfo() throws Exception {
            UserInfo userInfo = new UserInfo();
            userInfo.setAge(12);
            userInfo.setId(1000l);
            userInfo.setName("admin");
            userInfo.setNickname("管理员");
            userInfo.setPassword("123445");
            userInfoCacheDao.setUserInfo(userInfo);
        }
    
    }
    
    

    添加完成后,去查看发现,已经有已经生成。

    github
    中lessons-6

    相关文章

      网友评论

        本文标题:SpringBoot (六) :springboot与redis

        本文链接:https://www.haomeiwen.com/subject/eotbrxtx.html