【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 {   
    @Test
    public void method01(){       
        String host = "127.0.0.1"; 
        int port = 6379;
        Jedis jedis = new Jedis(host, port);  // 1. 创建连接,不用连接池       
        jedis.set("book","thinking");   // 2. 访问redis
        jedis.hset("student","name","zs");        
        jedis.close();  // 3. 关闭连接
        System.out.println("测试");
   }
    @Test
    public 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. 访问redis
        System.out.println(book);  //thinking      
        jedis.close();  //4. 将连接还给连接池
        pool.close(); // 销毁连接池,一般只有应用关闭时才用,释放内存
    }
    @Test
    public 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 {  
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    @Override
    protected 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转换为json
            jedis.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;
    @Override
    public 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 = -999000
    for 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:
            break
        if recv.strip():
            try:
                temp = int(float(recv.strip()) * 1000)
                if temp > max_temp:
                    max_temp = temp
            except 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 = -999000
    for 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 = temp
    print(max_temp)
update_qsfp_temp()

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

GIM: Learning Generalizable Image Matcher From Internet Videos

【引用格式】&#xff1a;Shen X, Yin W, Mller M, et al. GIM: Learning Generalizable Image Matcher From Internet Videos[C]//The Twelfth International Conference on Learning Representations. 2023. 【网址】&#xff1a;https://arxiv.org/pdf/2402.11095 【开源代…

使用 axios 进行 HTTP 请求

使用 axios 进行 HTTP 请求 文章目录 使用 axios 进行 HTTP 请求1、介绍2、安装和引入3、axios 基本使用4、axios 发送 GET 请求5、axios 发送 POST 请求6、高级使用7、总结 1、介绍 什么是 axios axios 是一个基于 promise 的 HTTP 库&#xff0c;可以用于浏览器和 Node.js 中…

高职人工智能专业实训课之“图像识别基础”

一、前言 随着人工智能技术的迅猛发展&#xff0c;高职院校对人工智能专业实训课程的需求日益迫切。唯众人工智能教学实训平台作为一所前沿的教育技术平台&#xff0c;致力于为学生提供高效、便捷的人工智能实训环境&#xff0c;特别在“图像识别基础”这一关键课程中&#xf…

JVM 相关知识整理

文章目录 前言JVM 相关知识整理1. 新生代和老年代2. 对象的分配过程3. Full GC /Major GC 触发条件4. 逃逸分析4.1.示例4.2. 使用逃逸分析&#xff0c;编译器可以对代码做如下优化 5. 对象的内存分配6. Minor GC 与 Major GC/Full GC的比较:7. 什么对象进入老年代7.1. 大对象直…

(4) cmake编译静态库和动态库

文章目录 静态库整体代码动态库编译整体代码执行结果(静态) 静态库整体代码 static.h #pragma onecevoid static_demo();static.cpp #include "static.h" #include <iostream>void static_demo(){std::cout<<"static demo"<<std::end…

深度学习增强的非线性光纤单像素成像系统

1、光子器件的逆向设计&#xff1a;通过机器学习&#xff0c;特别是深度学习&#xff0c;可以高效地进行光子器件的逆向设计&#xff0c;这在传统的多参数优化问题中尤为重要。 2、超构表面和超材料设计&#xff1a;机器学习被用于设计具有特定光学特性的超构表面和超材料&…

上位机图像处理和嵌入式模块部署(mcu和swd接口)

【 声明&#xff1a;版权所有&#xff0c;欢迎转载&#xff0c;请勿用于商业用途。 联系信箱&#xff1a;feixiaoxing 163.com】 最近学习mcu的时候&#xff0c;接触了不少调试器&#xff0c;这里面有daplink、st-link v2、j-link v9。虽然模块的形状可能不太一样&#xff0c;但…

力扣SQL50 销售分析III having + 条件计数

Problem: 1084. 销售分析III &#x1f468;‍&#x1f3eb; 参考题解 Code select s.product_id,p.product_name from sales s left join product p on s.product_id p.product_id group by product_id having count(if(sale_date between 2019-01-01 and 2019-03-31,1,nu…

OpenAPI

大家好我是苏麟 , 今天带来一个前端生成接口的工具 . 官网 : GitHub - ferdikoomen/openapi-typescript-codegen: NodeJS library that generates Typescript or Javascript clients based on the OpenAPI specification 安装命令 npm install openapi-typescript-codegen --sa…

对接Shopify电商平台的流程

对接Shopify平台的流程通常包括以下关键步骤&#xff0c;在整个对接过程中&#xff0c;需要密切关注Shopify的API使用限制、认证机制、数据隐私政策等&#xff0c;确保应用的安全性和合规性。北京木奇移动技术有限公司&#xff0c;专业的软件外包开发公司&#xff0c;欢迎交流合…

43 mysql insert select 的实现

前言 我们这里 来探讨一下 insert into $fields select $fields from $table; 的相关实现, 然后 大致来看一下 为什么 他能这么快 按照 我的思考, 应该里里面有 批量插入才对, 但是 调试结果 发现令我有一些意外 呵呵 果然 只有调试才是唯一的真理 测试数据表如下 CREATE…

企业中订单超时关闭是怎么做的?我说用延迟消息,面试官让我回去等消息?

文章目录 背景时序图方案对比方案一 被动关闭方案二 定时关闭方案三 Rocket MQ延迟消息 总结 背景 订单超时未支付是电商中的一个核心场景&#xff0c;当用户创建订单后&#xff0c;超过一定时间没有支付&#xff0c;平台需要及时将该订单关闭。需要关闭的主要原因有以下几个&…

基于springboot实现问卷调查系统项目【项目源码+论文说明】

基于springboot实现问卷调查系统演示 摘要 传统信息的管理大部分依赖于管理人员的手工登记与管理&#xff0c;然而&#xff0c;随着近些年信息技术的迅猛发展&#xff0c;让许多比较老套的信息管理模式进行了更新迭代&#xff0c;问卷信息因为其管理内容繁杂&#xff0c;管理数…

【database3】oracle:数据交换/存储/收集

文章目录 1.oracle安装&#xff1a;swap&#xff0c;dd1.1 创建swap交换区&#xff1a;grep MemTotal /proc/meminfo &#xff08;安装Oracle物理内存要求1024MB以上&#xff09;&#xff0c;grep SwapTotal /proc/meminfo1.2 安装依赖包及改系统核心参数&#xff1a;关闭一些系…

Selenium进行Web自动化测试

Selenium进行Web自动化测试 SeleniumPython实现Web自动化测试一、环境配置 SeleniumPython实现Web自动化测试 一、环境配置 环境基于win10&#xff08;X64&#xff09; 安装Python&#xff1b;安装PyCham安装chomedriver chomedriver下载地址 可以查看本地chrome软件版本下载…

【雷丰阳-谷粒商城 】【分布式高级篇-微服务架构篇】【13】压力压测JMeter-性能监控jvisualvm

持续学习&持续更新中… 守破离 【雷丰阳-谷粒商城 】【分布式高级篇-微服务架构篇】【13】压力压测JMeter-性能监控jvisualvm 压力测试概述性能指标 JMeter基本使用添加线程组添加 HTTP 请求添加监听器启动压测&查看分析结果JMeter Address Already in use 错误解决 性…

电子电气架构——由NRC优先级引起的反思

我是穿拖鞋的汉子,魔都中坚持长期主义的汽车电子工程师。 老规矩,分享一段喜欢的文字,避免自己成为高知识低文化的工程师: 屏蔽力是信息过载时代一个人的特殊竞争力,任何消耗你的人和事,多看一眼都是你的不对。非必要不费力证明自己,无利益不试图说服别人,是精神上的节…

matplotlib之savefig函数

savefig函数 Matplotlib中&#xff0c;savefig函数用于保存图形为文件。通过该函数&#xff0c;你可以将绘制的图形保存为常见的图像文件格式&#xff0c;如PNG、JPEG、SVG等。 matplotlib.pyplot.savefig(fname, dpiNone, bbox_inchestight, pad_inches0.1, formatNone, tra…

C++封装、继承、多态的应用---职工管理系统

C封装、继承、多态的应用—职工管理系统 文章目录 C封装、继承、多态的应用---职工管理系统1.需求分析2.抽象类的建立2.1抽象基类2.2员工类2.3经理类2.4老板类2.5存储类 3.抽象类的实现4.功能函数的实现4.1菜单功能的实现4.2增加职工功能函数实现4.2显示职工功能函数实现4.3删除…

初中英语优秀作文分析-005How to Plan Our Life Wisely-如何明智地规划我们的生活

PDF格式公众号回复关键字:SHCZYF005 记忆树 1 The “double reduction policy” reduces the burden on students and offers us more spare time than before, but how to plan our life wisely? 翻译 “双减政策”减轻了学生的负担&#xff0c;给了我们比以前更多的业余…