第三章 springboot + jedisCluster

如果使用的是redis2.x,在项目中使用客户端分片(Shard)机制。(具体使用方式:第九章 企业项目开发--分布式缓存Redis(1)  第十章 企业项目开发--分布式缓存Redis(2)

如果使用的是redis3.x中的集群,在项目中使用jedisCluster。

redis3.2.5集群搭建:第十二章 redis-cluster搭建(redis-3.2.5)

1、项目结构

2、pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xxx</groupId>
    <artifactId>myboot</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version><!-- 官方推荐 -->
    </properties>
    <!-- 引入spring-boot-starter-parent做parent是最好的方式,
         但是有时我们可能要引入我们自己的parent,此时解决方式有两种:
         1)我们自己的parent的pom.xml的parent设为spring-boot-starter-parent(没有做过验证,但是感觉可行)
         2)使用springboot文档中的方式:见spring-boot-1.2.5-reference.pdf的第13页
    -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.5.RELEASE</version>
    </parent>

    <!-- <dependencyManagement>
        <dependencies>
            <dependency>
                Import dependency management from Spring Boot
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>1.2.5.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement> -->

    <!-- 引入实际依赖 -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- 用于将应用打成可直接运行的jar(该jar就是用于生产环境中的jar) 值得注意的是,如果没有引用spring-boot-starter-parent做parent,
                且采用了上述的第二种方式,这里也要做出相应的改动 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

说明:相对于上一章的代码仅仅引入了jedis的依赖jar。

3、application.properties

#user info
user.id=1
user.username=zhaojigang
user.password=123

#redis cluster
redis.cache.clusterNodes=localhost:8080
redis.cache.commandTimeout=5
#unit:second
redis.cache.expireSeconds=120

说明:相对于上一章的代码仅仅引入了redis cluster的配置信息

4、Application.java(springboot启动类,与上一章一样)

5、RedisProperties.java(Redis属性装配)

package com.xxx.firstboot.redis;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "redis.cache")
public class RedisProperties {

    private int    expireSeconds;
    private String clusterNodes;
    private int    commandTimeout;

    public int getExpireSeconds() {
        return expireSeconds;
    }

    public void setExpireSeconds(int expireSeconds) {
        this.expireSeconds = expireSeconds;
    }

    public String getClusterNodes() {
        return clusterNodes;
    }

    public void setClusterNodes(String clusterNodes) {
        this.clusterNodes = clusterNodes;
    }

    public int getCommandTimeout() {
        return commandTimeout;
    }

    public void setCommandTimeout(int commandTimeout) {
        this.commandTimeout = commandTimeout;
    }

}

说明:与上一章的User类似,采用@ConfigurationProperties注解自动读取application.properties文件的内容并装配到RedisProperties的每一个属性中去。

6、JedisClusterConfig.java(获取JedisCluster单例)

package com.xxx.firstboot.redis;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

@Configuration
public class JedisClusterConfig {

    @Autowired
    private RedisProperties redisProperties;

    /**
     * 注意:
     * 这里返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用
     * @return
     */
    @Bean
    public JedisCluster getJedisCluster() {
        String[] serverArray = redisProperties.getClusterNodes().split(",");//获取服务器数组(这里要相信自己的输入,所以没有考虑空指针问题)
        Set<HostAndPort> nodes = new HashSet<>();

        for (String ipPort : serverArray) {
            String[] ipPortPair = ipPort.split(":");
            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
        }

        return new JedisCluster(nodes, redisProperties.getCommandTimeout());
    }

}

说明:

  • 该类注入了RedisProperties类,可以直接读取其属性
  • 这里没有对jedis链接池提供更多的配置(jedis-2.5.x好像不支持,jedis-2.6.x支持),具体的配置属性可以查看文章开头第一篇博客

注意:

  • 该类使用了Java注解,@Configuration与@Bean,

    • 在方法上使用@Bean注解可以让方法的返回值为单例,
    • 该方法的返回值可以直接注入到其他类中去使用
    • @Bean注解是方法级别的
  • 如果使用的是常用的spring注解@Component,
    • 在方法上没有注解的话,方法的返回值就会是一个多例,
    • 该方法的返回值不可以直接注入到其他类去使用
    • 该方式的注解是类级别的

7、MyRedisTemplate.java(具体redis操作)

package com.xxx.firstboot.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.JedisCluster;

@Component
public class MyRedisTemplate {
    private static final Logger LOGGER    = LoggerFactory.getLogger(MyRedisTemplate.class);

    @Autowired
    private JedisCluster        jedisCluster;

    @Autowired
    private RedisProperties     redisProperties;

    private static final String KEY_SPLIT = ":"; //用于隔开缓存前缀与缓存键值 

    /**
     * 设置缓存
     * @param prefix 缓存前缀(用于区分缓存,防止缓存键值重复)
     * @param key    缓存key
     * @param value  缓存value
     */
    public void set(String prefix, String key, String value) {
        jedisCluster.set(prefix + KEY_SPLIT + key, value);
        LOGGER.debug("RedisUtil:set cache key={},value={}", prefix + KEY_SPLIT + key, value);
    }

    /**
     * 设置缓存,并且自己指定过期时间
     * @param prefix
     * @param key
     * @param value
     * @param expireTime 过期时间
     */
    public void setWithExpireTime(String prefix, String key, String value, int expireTime) {
        jedisCluster.setex(prefix + KEY_SPLIT + key, expireTime, value);
        LOGGER.debug("RedisUtil:setWithExpireTime cache key={},value={},expireTime={}", prefix + KEY_SPLIT + key, value,
            expireTime);
    }

    /**
     * 设置缓存,并且由配置文件指定过期时间
     * @param prefix
     * @param key
     * @param value
     */
    public void setWithExpireTime(String prefix, String key, String value) {
        int EXPIRE_SECONDS = redisProperties.getExpireSeconds();
        jedisCluster.setex(prefix + KEY_SPLIT + key, EXPIRE_SECONDS, value);
        LOGGER.debug("RedisUtil:setWithExpireTime cache key={},value={},expireTime={}", prefix + KEY_SPLIT + key, value,
            EXPIRE_SECONDS);
    }

    /**
     * 获取指定key的缓存
     * @param prefix
     * @param key
     */
    public String get(String prefix, String key) {
        String value = jedisCluster.get(prefix + KEY_SPLIT + key);
        LOGGER.debug("RedisUtil:get cache key={},value={}", prefix + KEY_SPLIT + key, value);
        return value;
    }

    /**
     * 删除指定key的缓存
     * @param prefix
     * @param key
     */
    public void deleteWithPrefix(String prefix, String key) {
        jedisCluster.del(prefix + KEY_SPLIT + key);
        LOGGER.debug("RedisUtil:delete cache key={}", prefix + KEY_SPLIT + key);
    }

    public void delete(String key) {
        jedisCluster.del(key);
        LOGGER.debug("RedisUtil:delete cache key={}", key);
    }

}

注意:

这里只是使用了jedisCluster做了一些字符串的操作,对于list/set/sorted set/hash的操作,可以参考开头的两篇博客。

8、MyConstants.java(缓存前缀常量定义类)

package com.xxx.firstboot.common;

/**
 * 定义一些常量
 */
public class MyConstants {
    public static final String USER_FORWARD_CACHE_PREFIX = "myboot:user";// user缓存前缀
}

注意:

  • 根据业务特点定义redis的缓存前缀,有助于防止缓存重复导致的缓存覆盖问题
  • 缓存前缀使用":"做分隔符,这是推荐做法(这个做法可以在使用redis-desktop-manager的过程看出来)

9、UserController.java(测试)

package com.xxx.firstboot.web;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.xxx.firstboot.common.MyConstants;
import com.xxx.firstboot.domain.User;
import com.xxx.firstboot.redis.MyRedisTemplate;
import com.xxx.firstboot.service.UserService;

/**
 * @RestController:spring mvc的注解,
 * 相当于@Controller与@ResponseBody的合体,可以直接返回json
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @RequestMapping("/getUser")
    public User getUser() {
        return userService.getUser();
    }

    @RequestMapping("/testJedisCluster")
    public User testJedisCluster(@RequestParam("username") String username){
        String value =  myRedisTemplate.get(MyConstants.USER_FORWARD_CACHE_PREFIX, username);
        if(StringUtils.isBlank(value)){
            myRedisTemplate.set(MyConstants.USER_FORWARD_CACHE_PREFIX, username, JSON.toJSONString(getUser()));
            return null;
        }
        return JSON.parseObject(value, User.class);
    }

}

说明:相对于上一章,只是添加了测试缓存的方法testJedisCluster。

测试:

在Application.properties右击-->run as-->java application,在浏览器输入"localhost:8080/user/testJedisCluster?username=xxx"即可。

附:对于redis的测试,我们有时需要查看执行set后,缓存是否存入redis的db中了,有两种方式

  • 执行set后,get数据,之后修改数据,在get数据,比较两次get的数据是否相同即可
  • 有时,这些数据是无法修改的(假设该数据是我们从第三方接口得来的),这个时候可以使用redis-desktop-manager这个软件来查看缓存是否存入redis(该软件的使用比较简单,查看官网)
时间: 2024-08-30 06:02:11

第三章 springboot + jedisCluster的相关文章

第三章 SpringBoot 集成框架(二)

1.SpringBoot 默认能直接访问的静态资源目录: /static    public  /resources  /META-INF/resources 2.SpringBoot 集成 JSP :需要添加 JSP 的依赖 ,JSP 页面使用 JSTL 标签 . 3.SpringBoot 框架集成 JSP 时,打包的格式是war          打包:右键项目 --> Run as --> Maven build...    pom.xml中的打包方式:<packaging>

第二十五章 springboot + hystrixdashboard

注意: hystrix基本使用:第十九章 springboot + hystrix(1) hystrix计数原理:附6 hystrix metrics and monitor 一.hystrixdashboard 作用: 监控各个hystrixcommand的各种值. 通过dashboards的实时监控来动态修改配置,直到满意为止 仪表盘: 二.启动hystrix 1.下载standalone-hystrix-dashboard-1.5.3-all.jar https://github.com/

三、SpringBoot整合Thymeleaf

三.SpringBoot整合Thymeleaf As well as REST web services, you can also use Spring MVC to serve dynamic HTML content. Spring MVC supports a variety of templating technologies, including Thymeleaf, FreeMarker, and JSPs. Also, many other templating engines

构建之法前三章读后感

一. 软件作为一个产品,在提供用户使用前经历了许多工序,我们用工程的方式将开发软件的工序,过程加以工程化,系统化.成立了一套完整的体系后,有利于帮助我们开发软件,乃至于大型的系统. 软件具有一定的特殊性,使得软件工程师们做开发提升了一定的难度,但软件工程有助于软件系统的开发,帮助工程师们设计,构建,测试和维护软件.所以,软件工程的最终目的是帮助工程师们创造“足够好”的软件,提高软件的质量,用户满意度,可靠性,可维护性等. 第一章问题:怎么才算是一个真正的软件工程师? 二.   一个优秀的软件,通

0320 《构建之法》前三章观后感

第一章.为我们解释什么是软件,什么是软件工程,读完这章对这些概念有一定的认识这章让我明白,代码不能盲目的敲,好的软件并非两三天,并非一两个人就能赶出来的,需要大家的精诚合作.同时,在编写程序之前,还需要做一系列的分析.设计,要满足客户的需求,后续还要对软件进行测试.维护等.在这之前,我一直觉得能把程序运行,能有正确的结果,那就完成任务了,可这只是整个软件流程的一部分而已.看了邹老师的书,才知道其实创新有很多的方面,除了技术,还有商业思路,差异化等等,这些都给了我很大的感触,作为一名程序员,我们不

家庭作业——第三章

第三章家庭作业    3.69和3.70 3.69 A:long trace(tree_ptr tp)    {        long ret = 0;        while(tp != NULL)        {           ret = tp->val;           tp = tp->left;        }        return ret;    } B:作用是从根一直遍历左子树,找到第一个没有左子树的节点的值. 3.70 A:long traverse(t

第三章 Linux操作系统的安装

第三章 Linux操作系统的安装 因为笔者一直都是使用CentOS,所以这次安装系统也是基于CentOS的安装.把光盘插入光驱,设置bios光驱启动.进入光盘的欢迎界面. 其中有两个选项,可以直接按回车,也可以在当前界面下输入 linux text 按回车.前者是图形下安装,可以动鼠标的,后者是纯文字形式的.建议初学者用前者安装.直接回车后,出现一下界面: 这一步是要提示你是否要校验光盘,目的是看看光盘中的安装包是否完整或者是否被人改动过,一般情况下,如果是正规的光盘不需要做这一步操作,因为太费

《C#高级编程》【第三章】对象和类型 -- 学习笔记

在看过C++之后,再看C#的面向对象感觉就不难了,只是有一些区别而已. 1.类定义 使用class关键字来声明类,其和C++不同的地方是在大括号之后不需要冒号 class 类名 { //类的内部 } //C++这里有一个冒号,而C#没有 2.类成员 3.字段与属性 首先我们先区分一下C#数据成员中的字段.常量与事件成员.字段.常量是与类的相关变量.事件是类的成员,在发生某些行为时(如:改变类的字段或属性,或进行某种形式的用户交互操作),它可以让对象通知调用方. 那么现在我们在来看看字段与属性,属

标准库》第三章 包装对象和Boolean对象

第三部分  标准库 ***************第三章   包装对象和Boolean对象******************* 一.包装对象的定义[1]有人说,JavaScript语言"一切皆对象",数组和函数本质上都是对象,就连三种原始类型的值--数值.字符串.布尔值--在一定条件下,也会自动转为对象,也就是原始类型的"包装对象". 所谓"包装对象",就是分别与数值.字符串.布尔值相对应的Number.String.Boolean三个原生对象