前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot集成Redis集群就这么Easy

SpringBoot集成Redis集群就这么Easy

作者头像
JAVA葵花宝典
发布2019-05-29 16:19:48
2.6K0
发布2019-05-29 16:19:48
举报
文章被收录于专栏:JAVA葵花宝典JAVA葵花宝典

作者 l 孙亮亮

来源 l SpringForAll社区

这次写一下springboot与redis的结合,这里使用的是redis集群模式(主从),主从环境的搭建,请参考redis集群搭建

搭建完redis集群环境后,开始springboot之旅

1、REDIS介绍

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

2、项目构建

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

当然也可以自己添加pom文件,如下

代码语言:javascript
复制
<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-redis</artifactId></dependency>
3、添加配置文件

application.properties中

代码语言:javascript
复制
#-----------------------# start redis clusterjedis.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:7002jedis.cluster.testWhileIdle=truejedis.cluster.connectionTimeout=60jedis.cluster.soTimeout=60jedis.cluster.maxAttempts=1000jedis.cluster.password=12597758# end redis cluster config#---------------------------------
4、JEDIS配置类的编写

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

代码语言:javascript
复制
@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、通用接口的编写

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

代码语言:javascript
复制
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接口的实现
代码语言:javascript
复制
@Servicepublic 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的实现

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

代码语言:javascript
复制
@Componentpublic class UserInfoCacheDao extends JedisClusterClient<UserInfo> {    public void setUserInfo(UserInfo userInfo){        super.set("lessons.user:1",userInfo);    }}

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

8、单元测试
代码语言:javascript
复制
@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTestpublic 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);    }
}

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-05-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 JAVA葵花宝典 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、REDIS介绍
  • 2、项目构建
  • 3、添加配置文件
  • 4、JEDIS配置类的编写
  • 5、通用接口的编写
  • 6、接下来是JEDIS接口的实现
  • 7、业务DAO的实现
  • 8、单元测试
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档