开启redis服务和客户端

查看下当前redis的进程

[root@localhost ~]# ps -ef | grep redis

启动redis服务

[root@localhost ~]# cd /opt/redis-5.0.4
[root@localhost redis-5.0.4]# redis-server redis.conf

再查看下reids的服务进程

启动redis-cli

[root@localhost redis-5.0.4]# redis-cli -h 192.168.25.10 -p 6379

查看下keys

192.168.25.10:6379> keys *
1) "name"
2) "age"

使用 java 直接连接 redis 单机版

1.打开 IDEA ,创建maven项目 test_redis

点击 Enable Auto-Import, 自动引入依赖

2.在pom.xml中添加 redis单机版依赖


<?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/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.fan</groupId><artifactId>test_redis</artifactId><version>1.0-SNAPSHOT</version><dependencies><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>3.3.0</version></dependency></dependencies>
</project>

3.创建redis的测试类

package com.fan;import redis.clients.jedis.Jedis;/*** 测试java 连接redis*/
public class TestRedis {public static void main(String[] args) {Jedis jedis = new Jedis("192.168.25.10",6379);//参数1为 ip ,参数2为端口号//测试 redis 服务是否能正常连通String pang = jedis.ping();System.out.println(pang);}
}

测试运行

连接成功。

集群的节点也可以以单机的方式连接

设置值

package com.fan;import redis.clients.jedis.Jedis;/*** 测试java 连接redis*/
public class TestRedis {public static void main(String[] args) {Jedis jedis = new Jedis("192.168.25.10",6379);//参数1为 ip ,参数2为端口号//测试 redis 服务是否能正常连通String pang = jedis.ping();System.out.println(pang);//设置key-vale值String set = jedis.set("name", "zhangsan");System.out.println("返回值: "+set); //返回值为 OK//获取key的值String name = jedis.get("name");System.out.println("name: "+name);//向list1添加值Long list1 = jedis.lpush("list1", "3", "4", "5");System.out.println(list1);//设置key的过期时间jedis.expire("name",10);//可以在xshello中测试 tcl name,多执行几次看下效果//使用过之后关闭连接jedis.close();}
}

在XShell中执行 ttl name测试

注意: redis 服务 配置文件的bind属性必须是局域网ip 保护模式必须关闭

使用springboot 连接 redis 集群

一般是把redis集群当做spring boot 的缓存工具。

在service方法里访问的很多东西,有可能很少发生变化,每次查询数据库会比较慢。

可以在第一次查询的时候放到 redis 集群里面,下次会自动判断 redis 集群里有没有这块儿数据,有的话直接拿来用;没有的话,再去查数据库。

打开IDEA, 创建maven项目test_redis_02

第一步,添加依赖

<?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/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.fan</groupId><artifactId>test_redis_02</artifactId><version>1.0-SNAPSHOT</version><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.2.0.RELEASE</version></dependency><!--springboot集成redis的依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><version>2.2.0.RELEASE</version></dependency><!--mybatis-plus依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.3.1</version></dependency><!--mysql驱动依赖--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.20</version></dependency><!--数据源--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.1</version></dependency><!--lombok依赖--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.18</version></dependency></dependencies>
</project>

补充:安装 lombok依赖后,需要安装 lombok 插件,

使用lombok ,后面创建实体类不用再写get、set等方法了。

第二步、写配置文件 application.properties

在resources目录下,新建 application.properties文件

#连接数据库的配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/aaa?useUnicode=true&useSSL=false&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456#在控制台显示sql语句
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl#指定redis中的集群节点
spring.redis.cluster.nodes=192.168.25.10:7001,192.168.25.10:7002,192.168.25.10:7003,192.168.25.10:7004,192.168.25.10:7005,192.168.25.10:7006

第三步、写启动类

package com.fan;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;/*** springboot 启动类*/
@SpringBootApplication
@MapperScan("com.fan.dao") //扫描dao接口文件
//启动spring boot的缓存机制
@EnableCaching
public class WebStarter {public static void main(String[] args) {SpringApplication.run(WebStarter.class,args);}
}

第四步、把要缓存的实体类实现序列化接口

package com.fan.entity;import lombok.Data;import java.io.Serializable;/*** 用户管理实体类*/
@Data //lombok注解
public class Users implements Serializable {private Long id; //编号private String username;//用户名private String password;//密码
}

第五步、创建dao接口

package com.fan.dao;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fan.entity.Users;/*** 用户管理dao接口*/
public interface UsersDao extends BaseMapper<Users> {}

第六步、创建service层

package com.fan.service;import com.fan.dao.UsersDao;
import com.fan.entity.Users;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.List;/*** 用户管理servcie实现类*/
@Service
public class UsersService {@Resourceprivate UsersDao usersDao;/*** 查询所有的用户信息* @return*/public List<Users> listAll(){List<Users> users = usersDao.selectList(null);return users;}
}

第七步、创建用户管理控制器

package com.fan.controller;import com.fan.entity.Users;
import com.fan.service.UsersService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;
import java.util.List;/*** 用户管理控制器*/
@RestController
public class UsersController {@Resourceprivate UsersService usersService;/*** 查询所有用户* @return*/@RequestMapping("/listAll")public List<Users> listAll(){return usersService.listAll();}
}

第八步、启动测试

运行项目的启动类。

在浏览器中输入 http://localhost:8080

可以看到idea的控制台打印显示了 sql语句

在要缓存数据的方法上加 springboot 提供的缓存注解

@Cacheable

指如果redis缓存中有数据,就直接从缓存中取数据,如果没有数据,去数据库查询,往缓存中放一份,然后再返回数据。

第一次访问这个方法,缓存没有数据,去查询数据 库。第二次访问,缓存中有数据,就不用再查询数据库,查缓存就可以了。

第一次启动访问时,控制台显示查询sql语句的信息。

在浏览器中访问 http://localhost:8080/listAll

清除控制台信息。再访问 http://localhost:8080/listAll,可以发先idea控制台不再打印sql信息。说明再第二次访问的时候直接查询页面缓存。

连接redis-cli, 看下数据库特征

[root@localhost ~]# redis-cli -c -h 192.168.25.10 -p 7001
192.168.25.10:7001> keys *
1) "listAll::SimpleKey []"192.168.25.10:7001> 

在@Cacheable注解添加参数 key=“test”

重新启动,测试访问

idea控制台也有报错信息, 提示 test 属性或字段在spring缓存中不能被发现,不是公共的…

key对应的是一个变量

key= “‘test’”

重新启动测试访问

idea控制台打印显示sql日志信息

再看下redis中的数据库的特征


UsersController

    @RequestMapping("/findById")public Users findById(Long id){Users users = usersService.findById(id);return users;}

UsersService

    /*** 根据用户id 查询用户信息* @param id* @return*/@Cacheable(value = "findById",key = "#id",condition = "#id%2==0")  //condition 条件public Users findById(Long id){Users users = usersDao.selectById(id);return users;}

id为奇数

再运行还会在控制台打印sql日志信息

可以看到没有存到数据库

清除控制台信息

id为偶数

就不再查询数据库,直接查询redis

@CachePut

无论缓存中是否有数据,都把缓存覆盖一次,也就是更新缓存。

@CacheEvict

每次执行方法 都会把指定的key的缓存清空

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TSvdlxVc-1616416717292)(.\img\26.png)]

如果要清除 listAll的结果,可以写个方法

UsersService.java

//调用这个方法的时候会把listAll的请求的缓存清除掉@CacheEvict(value = "listAll")public void clearListAll(){System.out.println("清空listAll缓存");}

UsersController.java

    /*** 根据用户id 查询用户信息* @return*/@RequestMapping("/clearListAll")public String clearListAll(){usersService.clearListAll();return "success";}

启动测试,在浏览器中访问 http://localhost:8080/clearListAll

看下redis缓存

可以看到把不带任何参数、不带key的listAll清除掉了。

把所有listAll开头的都删除掉, 添加 allEntries = true

allEntries作用就是忽略key 的值

     @CacheEvict(value = "listAll",allEntries = true)public void clearListAll(){System.out.println("清空listAll缓存");}

以上两个注解用的不多,用的比较多的是:

spring boot 启用缓存之后为我们在spring 容器中创建的一个内置对象 RedisTemplate

UsersService.java

    @Autowiredprivate RedisTemplate redisTemplate; //相当于Jedis/*** 测试redisTemplate*/public void testRedisTemplate(){System.out.println(this.redisTemplate);}

在控制器中调用这个方法

    /*** 测试redisTemplate* @return*/@RequestMapping("/testRedisTemplate")public String testRedisTemplate(){usersService.testRedisTemplate();return "success";}

启动调试,打断点

    /*** 测试redisTemplate*/public void testRedisTemplate(){this.redisTemplate.opsForValue().set("test","value",1000, TimeUnit.SECONDS);//操作string类型数据this.redisTemplate.expire("test",4000,TimeUnit.SECONDS);}

springboot连接redis集群相关推荐

  1. SpringBoot连接Redis集群时发生错误Cannot determine a partition to read for slot

    今天做SpringBoot和Redis整合时发生错误 io.lettuce.core.cluster.PartitionSelectorException: Cannot determine a pa ...

  2. springboot整合redis集群master宕机后连接超时

    前提: #        本文是在确保redis集群配置正确的情况下,连接超时的解决方案. 项目登录认证使用的是sa-token(这个不重要,主要说的是springboot和redis集群),最近应甲 ...

  3. java集群解析文件_java相关:springboot整合redis集群过程解析

    java相关:springboot整合redis集群过程解析 发布于 2020-4-13| 复制链接 摘记: 简介 在springboot使用搭建好的redis集群添加redis和连接池依赖 ```x ...

  4. 什么是slot槽节点、Springboot集成Redis集群

    一. 什么是slot槽节点 slots:槽,用于装数据,主节点有,从节点没有 1.怎么分配slot? --平均分配 需要注意的是,槽节点是分配给master节点的,slave节点没有.  2.槽slo ...

  5. springboot集成redis集群实现集群拓扑动态刷新

    一个redis-cluster的三主三从集群,在其中一个master节点挂了之后,springboot集成redis集群配置信息没有及时刷新,出现读取操作报错.下面聊聊如何实现springboot集成 ...

  6. Jedis连接Redis集群

    连接集群版 把jedis依赖的jar包 添加到工程中 //连接redis集群 @Test public void testJedisCluster() throws Exception {//创建一个 ...

  7. SpringBoot整合Redis集群版本问题

    QUESTION:SpringBoot整合Redis集群版本问题? ANSWER: 版本依赖: <dependencies><!-- https://mvnrepository.co ...

  8. 连接redis集群报错: no reachable node in cluster

    今天在连接redis集群时遇到个问题,试了很多方案也没解决. 就是连接redis集群老是报错: no reachable node in cluster. 后来改了一些参数,就可以调通了. 废话不多说 ...

  9. lua 连接redis集群

    1.连接redis集群需要用到llua-resty-redis-cluster模块 github地址:https://github.com/cuiweixie/lua-resty-redis-clus ...

最新文章

  1. android x86一键安装,安卓
  2. javascript总结9:JavaScript三目运算符
  3. 会计学研究生课程有计算机吗,2018考研:会计专业有哪些研究方向?
  4. redis3.0伪集群安装步骤
  5. MySQL 5.5 日志管理
  6. VMware安装Windows Server 2003提示Operating System not found
  7. Eucalyptus环境搭建
  8. php goeasy,Goeasy数据推送 - 使用goeasy由后端向前端推送数据 – 基于ThinkPHP和Bootstrap的极速后台开发框架...
  9. linux内核手写板驱动,【Linux系统编程应用】 Linux Input子系统(一)
  10. echarts柱状图显示百分比
  11. 多终端登录,只保留一个移动端+PC端同时在线
  12. 华为电脑 鸿蒙,微软宣布Win10装机量突破10亿,唯独华为电脑不能安装,鸿蒙极速反击...
  13. HDOJ 3911 线段树
  14. Python Curses
  15. 研一(研究生)看论文文献必须要知道的几个网站
  16. 开源MPEG-4编码器 XviD简介
  17. 怎样用python写引流脚本
  18. [问题已处理]-阿里云服务器种了蠕虫病毒和恶意下载病毒处理
  19. RAP2 接口Mock工具部署使用
  20. Oracle表空间满了该如何解决?

热门文章

  1. 一文教你生成SSL自认证证书
  2. 图文传授win10系统设置临时环境变量的方法
  3. Java基础2019最新Java面试经典题解析
  4. linux mkfifo 命令_Linux高级命令——mkfifo的使用
  5. Optimizer优化器
  6. Halcon 学习之焊点提取
  7. 时隔一个月,讯飞星火大模型 V1.5 发布:星火 APP 登场,综合能力升级
  8. Pandas中isin函数 Dataframe提取(删除)指定行列
  9. mysql中int长度的意义
  10. Unity 可调控概率