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

文章介绍了Redis的安装,包括配置文件加载和使用Jedis连接Redis进行数据操作。接着展示了一个好友列表的案例,从前端HTML、Servlet、服务层到DAO层如何使用Redis缓存数据。讨论了数据库优化,如存储过程和触发器,以及SQL查询优化。此外,提到了数据库的冷热备份方法。最后,文章提及了Redis的订阅功能和Python示例。
摘要由CSDN通过智能技术生成


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()
  • 0
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农编程录

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值