【database2】redis:优化/备份/订阅

文章目录

  • 1.redis安装:加载.conf
  • 2.操作:set/get,push/pop,add/rem
  • 3.Jedis:java程序连接redis,拿到jedis
  • 4.案例_好友列表:json = om.
    • 4.1 前端:index.html
    • 4.2 web:FriendServlet .java
    • 4.3 service:FriendService.java
    • 4.4 dao:FriendDao.java
    • 4.5 bean:Friend.java
  • 5.数据库优化:存储过程(PL/SQL代码集,像没有返回值的自定义函数)和函数需要用户显示调用才执行,而触发器是由一个事件来触发运行,当某个事件发生时会自动地隐式运行,不能被显示的调用。sql多用group by
  • 6.数据库备份和恢复:冷热备份
  • 7.订阅: channel和key没有关系


1.redis安装:加载.conf

朋友圈数据缓存在手机内存,视频大量弹幕即海量数据先缓存再写入关系型数据库。如下两个存储文件第一次用是没有的。蓝横线是上一行的快捷方式,右击属性最后加上空格x.conf文件路径。Mysql默认3306端口,tomcat默认8080端口。
在这里插入图片描述
redis-cli.exe命令行客户端不好用,用图形化客户端redis-desktop-manager-0.7.6.15.exe:链接:https://pan.baidu.com/s/1iJZcnSbRsejUgTlfxu_EKQ 提取码:f8ym 。Add New Connection如下:
在这里插入图片描述
redis服务器软件关了, 没有reload就不会保存。redis安装后默认有16个仓库,默认使用db0,用select换数据库。
在这里插入图片描述

2.操作:set/get,push/pop,add/rem

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
如下list重索序,不需要知道集合长度,遍历只要0到-1索引。
在这里插入图片描述
在这里插入图片描述
如下理解score是分数可重复。
在这里插入图片描述
在这里插入图片描述

3.Jedis:java程序连接redis,拿到jedis

如下放入web/WEB-INF/lib并右击add as library。
在这里插入图片描述

package com.itheima01.jedis;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;public class JedisDemo {   @Testpublic void method01(){       String host = "127.0.0.1"; int port = 6379;Jedis jedis = new Jedis(host, port);  // 1. 创建连接,不用连接池       jedis.set("book","thinking");   // 2. 访问redisjedis.hset("student","name","zs");        jedis.close();  // 3. 关闭连接System.out.println("测试");}@Testpublic void method02(){       String host = "127.0.0.1";int port = 6379;JedisPoolConfig config = new JedisPoolConfig(); //连接池config.setMaxTotal(5); //最大连接数config.setMaxWaitMillis(2000); // 最长等待时间config.setMaxIdle(2); // 最大空闲数:最多允许两个连接不干活,超过两个会被回收掉,达到释放内存目的JedisPool pool = new JedisPool(config, host, port); //1. 初始化连接池        Jedis jedis = pool.getResource(); //2. 获取连接       String book = jedis.get("book"); //3. 访问redisSystem.out.println(book);  //thinking      jedis.close();  //4. 将连接还给连接池pool.close(); // 销毁连接池,一般只有应用关闭时才用,释放内存}@Testpublic void method03(){ //测试封装的框架Jedis jedis = JedisUtil.getResource();String book = jedis.get("book");System.out.println(book + "-------");jedis.close();}
}
package com.itheima01.jedis;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.ResourceBundle;public class JedisUtil {private static JedisPool pool;/* static{String host = "127.0.0.1";int port = 6379;JedisPoolConfig config = new JedisPoolConfig();config.setMaxTotal(5);  //最大连接数config.setMaxWaitMillis(2000);  // 最长等待时间config.setMaxIdle(2);  // 最大空闲数pool = new JedisPool(config, host, port);}*///如下用jedis.properties替代如上 /*static{Properties p = new Properties();InputStream is = JedisUtil.class.getClassLoader().getResourceAsStream("jedis.properties");try { p.load(is);String host = p.getProperty("host");Integer port = Integer.parseInt(p.getProperty("port"));Integer maxTotal = Integer.parseInt(p.getProperty("maxTotal"));Integer maxWaitMillis = Integer.parseInt(p.getProperty("maxWaitMillis"));Integer maxIdle = Integer.parseInt(p.getProperty("maxIdle"));            //如下同上面JedisPoolConfig config = new JedisPoolConfig();config.setMaxTotal(maxTotal); //最大连接数config.setMaxWaitMillis(maxWaitMillis); // 最长等待时间config.setMaxIdle(maxIdle); // 最大空闲数pool = new JedisPool(config, host, port);} catch (IOException e) { //输入流有异常e.printStackTrace();}}*///如下可替代如上 static{/** ResourceBundle : 资源堆,用来替代Properties成为properties文件专属解析类*    1. 底层: 类加载器  -> 文件必须放在src下*    2. 只能加载properties文件 -> 文件的后缀名.properties不要写。*/ResourceBundle bundle = ResourceBundle.getBundle("jedis");String host = bundle.getString("host");Integer port = Integer.parseInt(bundle.getString("port"));Integer maxTotal = Integer.parseInt(bundle.getString("maxTotal"));Integer maxWaitMillis = Integer.parseInt(bundle.getString("maxWaitMillis"));Integer maxIdle = Integer.parseInt(bundle.getString("maxIdle"));//如下同上面JedisPoolConfig config = new JedisPoolConfig();config.setMaxTotal(maxTotal); //最大连接数config.setMaxWaitMillis(maxWaitMillis); // 最长等待时间config.setMaxIdle(maxIdle); // 最大空闲数pool = new JedisPool(config, host, port);}public static Jedis getResource(){Jedis jedis = pool.getResource();return jedis;}
}
//jedis.properties文件 
host = 127.0.0.1
port = 6379
maxTotal = 5
maxWaitMillis = 2000
maxIdle = 2

4.案例_好友列表:json = om.

4.1 前端:index.html

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

//index.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><script src="js/jquery-3.3.1.min.js"></script><script>$(function () { //页面加载事件$.get("/FriendServlet","",function (data) { //data// console.log(data)var content = ""$(data).each(function (index,element) {content += "<li>" + element.name + "</li>"})$("#myid").html(content) //因为<li>是html},"json")})</script>
</head><!--111111111111111111111111111111111111111111111111111111111111-->
<body><ul id="myid"></ul>
</body>
</html>

在这里插入图片描述
如下就是index.html效果。
在这里插入图片描述
在这里插入图片描述

4.2 web:FriendServlet .java

package com.heima.example.web;
import com.heima.example.service.FriendService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@WebServlet(urlPatterns = "/FriendServlet")
public class FriendServlet extends HttpServlet {  @Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {FriendService service = new FriendService(); //调用service层代码String json = service.findAllFriend();response.setContentType("text/html;charset=utf-8");response.getWriter().print(json);}
}

4.3 service:FriendService.java

package com.heima.example.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.example.bean.Friend;
import com.heima.example.dao.FriendDao;
import com.itheima01.jedis.JedisUtil;
import com.sun.org.apache.bcel.internal.generic.NEW;
import redis.clients.jedis.Jedis;
import java.util.List;
/*
*  service层: 业务逻辑 + 缓存 cache
*  缓存弊端: 数据不更新 (查询走缓存,如果执行增删改, 重新查询数据库,更新缓存)
*  如上括号里的更新缓存也会存在缓存延迟的情况(如朋友圈删除动态有时也能看见)
*  朋友圈不是实时同步,如果实时同步对服务器来说压力大。好友列表的在线状态是实时同步的,用心跳长连接。
*/
public class FriendService { //service文件夹下
//选中再ctrl + shift + u转为大写,"example_friend_list"变量改了,全局FRIEND_LIST_CACHE常量不用改public static final String FRIEND_LIST_CACHE = "example_friend_list"; public String findAllFriend() throws JsonProcessingException {        Jedis jedis = JedisUtil.getResource();String json = jedis.get(FRIEND_LIST_CACHE); //直接从缓存里取if(json == null){ //就从mysql数据库中取                      FriendDao dao = new FriendDao();List<Friend> list = dao.findAll();                         ObjectMapper om = new ObjectMapper();json = om.writeValueAsString(list); //list转换为jsonjedis.set(FRIEND_LIST_CACHE,json); //记得往缓存里放一份json即字符串System.out.println("从mysql中查");}else{System.out.println("从redis中查");}jedis.close(); //记得还给连接池,不然5个用完就崩了return json;}
}

4.4 dao:FriendDao.java

package com.heima.example.dao;
import com.heima.example.bean.Friend;
import com.heima.example.utils.JdbcUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;public class FriendDao {  //Dao文件夹下public List<Friend> findAll() {String sql = "select * from user";JdbcTemplate template = JdbcUtil.getTemplate();List<Friend> list = template.query(sql, new BeanPropertyRowMapper<>(Friend.class));return list;}
}

4.5 bean:Friend.java

package com.heima.example.bean;public class Friend { //bean文件夹下private Integer id;private String name;private String password;@Overridepublic String toString() {return "Friend{" +"id=" + id +", name='" + name + '\'' +", password='" + password + '\'' +'}';}    public Integer getId() {return id;}    public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}

如下刷新浏览器index.html页面。
在这里插入图片描述
在这里插入图片描述

5.数据库优化:存储过程(PL/SQL代码集,像没有返回值的自定义函数)和函数需要用户显示调用才执行,而触发器是由一个事件来触发运行,当某个事件发生时会自动地隐式运行,不能被显示的调用。sql多用group by

如下都是sql语句优化:1. 数据库开启缓存,多次相同查询,结果放入缓存,不会从表中提取。

2.explain检查SQL查询(explain select…)。

3. where后面字段建立索引。

4. limit 1,查到一行就不继续往下走。

5. 大量insert或delete时会把表整个锁起来,导致大量web服务器请求过来进不去表,导致宕机,所以用limit进行拆分。

6. 数据类型尽量用小的,不同数据类型占用硬盘空间不一样,如果占用硬盘空间小且紧凑,这样硬盘数据读写快。

7. 固定字段长度,字段长度统一,数据库计算偏移量轻松。从前端查出来的数据会多出来一些空格,用trim去除空格再封装进对象。

8. 报错:该对象属性不为null或mysql查询数据为null…,用’空格’。数据库一字段查出赋值到java对象上,如果字段为null会报空指针异常。

9. 明确固定字段用enum(性别,市),enum速度比varchar快。

10. 不管任何方式查询表,最终都会通过主键定位到数据,建立主键会有效提高性能。id主键多用int速度比varchar快。

11. 避免使用rand(),order by rand()把数据库累死。

12. 两个字段类型一致,连接两表用join。

6.数据库备份和恢复:冷热备份

1.冷备份:适用于myisam引擎,不适用于innoDB引擎:关闭mysql,如下或可以点进book文件夹里将.frm(表结构)和.MYD(表数据)和.MYI(表索引)文件拷贝出来,这三个组合到一起就是一张表,恢复的时候只需把你copy出来的这些文件再重新粘贴回去即可。
在这里插入图片描述
2.热备份:执行mysql安装目录下的bin/里面的这个mysqldump.exe工具。mysqldump是工具 -u是用户名 -p是密码 -A是全部的意思 -d是表结构 -t是表数据 > 是重定向的意思 > 右边是需要输出的路径和文件名。
2.1 全备份:mysqldump -uroot -p123456 -A > /back/backdb.sql
2.2 备份指定库命令:mysqldump -uroot -p123456 db1,db2 > /back/backdb.sql
2.3 备份指定表命令:mysqldump -uroot -p123456 db1 tb1 tb2, db2 tb2> /back/backdb.sql
2.4 备份表结构命令:mysqldump -uroot -p123456 -A -d > /back/backdb.sql
2.5 备份表数据命令:mysqldump -uroot -p123456 -A -t > /back/backdb.sql
2.6 恢复:source命令在执行时会显示详细信息,能看到执行到哪出错了:source /back/backdb.sql
float(8,6)小数点前面占2位,小数点后面占6位。

7.订阅: channel和key没有关系

# meta-byte/meta-hp/recipes-core/packagegroups/packagegroup-core-tools-debug.bbappend
MTRACE = ""
MTRACE:libc-glibc = ""
RDEPENDS:${PN} += " \python3-pytz \python3-redis \
"# 如下采用接口的publish(发布)和 subscribe(订阅)方式要知道channel
import redis  # 如上安装才有
redis_client = redis.Redis(host='240.1.1.1', port=6379, db=6)
pubsub = redis_client.pubsub()
pubsub.subscribe("mychannel")
for message in pubsub.listen():print(message)import redis
redis_client = redis.Redis(host='127.0.0.1', port=6379, db=6)
redis_client.publish("mychannel","333")

采用psubscribe方式,无法获取key的value值变化,只能获取事件如hset动作,如下在bmc中用命令直接get,可以获取key的value变化(插拔光模块有变化)。
在这里插入图片描述
在这里插入图片描述
如下没法订阅整个db。
在这里插入图片描述

# a.py , time ./a.py
#!/usr/bin/python3
from hal.hal_temp import *
def update_qsfp_temp():max_temp = -999000for i in range(1, 41):cmd = f"redis-cli -h 240.1.1.1 -p 6379 -n 6 hget 'TRANSCEIVER_DOM_SENSOR|ethernet{i}' temperature"recv, ret = hal_run_bmc_cmd(cmd)if ret or "Could not connect" in recv:breakif recv.strip():try:temp = int(float(recv.strip()) * 1000)if temp > max_temp:max_temp = tempexcept ValueError:syslog.syslog(syslog.LOG_INFO, f"Invalid temperature value received for ethernet{i}: '{recv.strip()}'")
update_qsfp_temp()#!/usr/bin/python3
import redis
def update_qsfp_temp():redis_pool = redis.ConnectionPool(host='240.1.1.1', port=6379, db=6)redis_client = redis.Redis(connection_pool=redis_pool)max_temp = -999000for i in range(1, 41):key = f"TRANSCEIVER_DOM_SENSOR|ethernet{i}"temp = redis_client.hget(key, "temperature")if temp is not None:temp = int(float(temp.decode()) * 1000)if temp > max_temp:max_temp = tempprint(max_temp)
update_qsfp_temp()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/32727.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

谈谈面试常考题:懒加载,防抖,节流(方法实现详解)

前言 最近在学习中确实收获了挺多东西&#xff0c;其中我觉得有必要拿来进行分享一下的就是懒加载了&#xff0c;还有相关的防抖和节流。因为在浏览器中这些都是属于很常见的性能优化&#xff0c;面试也是常考题。话不多说&#xff0c;速度发车。 什么是懒加载&#xff1f;懒…

热题系列章节6

297. 二叉树的序列化与反序列化 序列化是将一个数据结构或者对象转换为连续的比特位的操作&#xff0c;进而可以将转换后的数据存储在一个文件或者内存中&#xff0c;同时也可以通过网络传输到另一个计算机环境&#xff0c;采取相反方式重构得到原数据。 请设计一个算法来实现…

Android面试题精选——再聊Android-Handler机制

​ static final ThreadLocal sThreadLocal new ThreadLocal(); //创建当前线程的Looper对象 private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() ! null) { throw new RuntimeException(“Only one Looper may be created per thread”); } sThre…

华为欧拉 openEuler24.03 更新 阿里 yum源

华为欧拉 openEuler24.03 更新 阿里 yum源 备份 yum 源编写 阿里云 yum源 配置文件更新 yum 缓存 备份 yum 源 mv /etc/yum.repos.d/openEuler.repo /etc/yum.repos.d/openEuler.repo.bak编写 阿里云 yum源 配置文件 vim /etc/yum.repos.d/openEuler.repo内容如下&#xff…

【进阶篇-Day5:JAVA常用API的使用(Math、BigDecimal、Object、包装类等)】

目录 1、API的概念2、Object类2.1 Object类的介绍2.2 Object的toString()方法2.3 Object的equals()方法2.4 Objects概述 3、Math类4、System类5、BigDecimal类6、包装类6.1 包装类的概念6.2 几种包装类&#xff08;1&#xff09;手动转换包装类&#xff1a;&#xff08;2&#…

pg分区表和mysql分区表的创建及删除添加操作

一、分区的类型 1、pg分区的类型 范围划分 列表划分 哈希分区 2、mysql分区的类型 范围分区 列表分区 hash分区 列分区 密匙分区 子分区 二、pg范围分区表的创建删除添加操作 1、pg分区表的创建 2、pg的分区表删除 3、pg分区表的添加 创建新的子分区 添加新创建的子分区 …

python 字符串驻留机制

偶然发现一个python字符串的现象&#xff1a; >>> a 123_abc >>> b 123_abc >>> a is b True >>> c abc#123 >>> d abc#123 >>> c is d False 这是为什么呢&#xff0c;原来它们的id不一样。 >>> id(a)…

浙大宁波理工学院2024年成人高等继续教育招生简章

浙大宁波理工学院&#xff0c;这所承载着深厚学术底蕴和卓越教育理念的学府&#xff0c;正热烈开启2024年成人高等继续教育的招生之门。这里&#xff0c;是知识的殿堂&#xff0c;是智慧的摇篮&#xff0c;更是您实现个人梦想、追求更高境界的起点。 ​浙大宁波理工学院始终坚…

实战指南:部署Elasticsearch 8.4.1与Kibana 8.4.1并集成IK分词器

首先拉取elasticsearch和kibana镜像 docker pull elasticsearch:8.4.1 docker pull kibana:8.4.1如果遇到镜像拉去不下来&#xff0c;遇到如下问题&#xff1a; [ERROR] error pulling image configuration: Get " https://production.cloudflare.docker.com/registry-v…

【吊打面试官系列-Mysql面试题】视图有哪些优点?

大家好&#xff0c;我是锋哥。今天分享关于 【视图有哪些优点&#xff1f;】面试题&#xff0c;希望对大家有帮助&#xff1b; 视图有哪些优点&#xff1f; 答&#xff1a; (1) 视图能够简化用户的操作&#xff1b; (2) 视图使用户能以多种角度看待同一数据&#xff1b; (3) 视…

【C#】使用数字和时间方法ToString()格式化输出字符串显示

在C#编程项目开发中&#xff0c;几乎所有对象都有格式化字符串方法&#xff0c;其中常见的是数字和时间的格式化输出多少不一样&#xff0c;按实际需要而定吧&#xff0c;现记录如下&#xff0c;以后会用得上。 文章目录 数字格式化时间格式化 数字格式化 例如&#xff0c;保留…

【docker1】指令,docker-compose,Dockerfile

文章目录 1.pull/image&#xff0c;run/ps&#xff08;进程&#xff09;&#xff0c;exec/commit2.save/load&#xff1a;docker save 镜像id&#xff0c;不是容器id3.docker-compose&#xff1a;多容器&#xff1a;宿主机&#xff08;eth0网卡&#xff09;安装docker会生成一…

4、SpringMVC 实战小项目【加法计算器、用户登录、留言板、图书管理系统】

SpringMVC 实战小项目 3.1 加法计算器3.1.1 准备⼯作前端 3.1.2 约定前后端交互接⼝需求分析接⼝定义请求参数:响应数据: 3.1.3 服务器代码 3.2 ⽤⼾登录3.2.1 准备⼯作3.2.2 约定前后端交互接⼝3.2.3 实现服务器端代码 3.3 留⾔板实现服务器端代码 3.4 图书管理系统准备后端 3…

【电路笔记】-共发射极放大器

共发射极放大器 文章目录 共发射极放大器1、概述2、完整的CEA配置3、直流等效电路4、交流等效电路5、输入阻抗6、输出阻抗7、电压增益8、微分电容的重要性9、信号源的衰减10、电流增益11、相位反转12、总结1、概述 在本文中,我们将介绍基于双极晶体管的放大器的最后一种拓扑:…

2024 WaniCTF repwn 部分wp

lambda 文本编辑器打开附件 稍微格式化一下 结合gpt理解题目意思。 脚本 home 附件拖入ida 简单的检查环境和反调试&#xff0c;进构造flag的函数 简单的ollvm&#xff0c;用d810嗦一下 下断点调试&#xff0c;通过修改eip跳过反调试。查看dest内容&#xff0c;需要稍微向下翻一…

QT中利用动画弄一个侧边栏窗口,以及贴条效果

1、效果 2、关键代码 void Widget::on_sliderBtn_clicked() {m_sliderWidget->show();QPropertyAnimation* animation = new QPropertyAnimation(m

第14章. GPIO简介

目录 0. 《STM32单片机自学教程》专栏 14.1 GPIO基本结构 14.1.1 保护二极管 14.1.2 上拉、下拉电阻 14.1.3 施密特触发器 14.1.4 P-MOS 管和 N-MOS 管 14.1.5 输出数据寄存器 14.1.6 输入数据寄存器 14.2 GPIO工作模式 14.2.1 输入模式 14.2.1.1 输入浮空模式 1…

ABB机器人教程:工具载荷与有效载荷数据自动标定操作方法

目录 概述 工具载荷自动标定前的准备工作 进入载荷识别服务例行程序 工具载荷识别与标定操作 有效载荷识别与标定操作要点 4轴码垛类型机器人载荷数据标定说明 概述 在使用ABB机器人前需要正确标定一些关键数据&#xff0c;其中就包含载荷数据。理论上讲&#xff0c;安装…

issues.sonatype.org网站废弃,Maven仓库账号被废弃问题解决

问题起因&#xff1a; 今天自己的项目发布了一个新版本&#xff0c;打算通过GitHub流水线直接推送至Maven中央仓库&#xff0c;结果发现报错 401&#xff0c;说我的账号密码认证失败。我充满了疑惑我寻思难度我的号被盗掉了吗。于是我打开Nexus Repository Manager尝试登录账号…

【b站-湖科大教书匠】2 物理层-计算机网络微课堂

课程地址&#xff1a;【计算机网络微课堂&#xff08;有字幕无背景音乐版&#xff09;】 https://www.bilibili.com/video/BV1c4411d7jb/?share_sourcecopy_web&vd_sourceb1cb921b73fe3808550eaf2224d1c155 目录 2 物理层 2.1 物理层的基本概念 2.2 物理层下面的传输媒…