前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[PostgreSQL数据库序列生成器 ]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
PostgreSQL
如何使用PostgreSQL的序列生成器(SEQUENCE)来自动生成序列号? 随着数据库应用的普及,序列生成器越来越受到开发者的青睐。今天,我们就来深入了解一下PostgreSQL中的序列生成器——SEQUENCE。 1. 序列生成器的基本概念 首先,我们来看看什么是序列生成器。简单来说,序列生成器就是一种特殊的数据库对象,它可以为我们自动生成一组唯一的、递增的数字。咱们可以通过给定初始数字、步长大小和上限值,来灵活掌控生成的数字区间,确保这些数字一个萝卜一个坑,既不会重复,又能连贯有序地生成。就像是在数轴上画一条连续不断的线段,从起点开始,按照我们设定的步长逐个“蹦跶”,直到达到我们预设的最大值为止。 2. 创建序列生成器 在PostgreSQL中,我们可以使用CREATE SEQUENCE语句来创建一个新的序列生成器。下面是一个简单的例子: sql CREATE SEQUENCE my_sequence; 以上代码将会创建一个新的名为my_sequence的序列生成器。默认情况下,它的初始值为1,步长为1,没有最大值限制。 3. 使用序列生成器 有了序列生成器之后,我们就可以在插入数据的时候方便地获取下一个唯一的数字了。在PostgreSQL中,我们可以使用SELECT NEXTVAL函数来获取序列生成器的下一个值。下面是一个例子: sql INSERT INTO my_table (id) VALUES (NEXTVAL('my_sequence')); 以上代码将会向my_table表中插入一行数据,并将自动生成的下一个数字赋给id列。注意,我们在括号中指定了序列生成器的名字,这样PostgreSQL就知道应该从哪个序列生成器中获取下一个值了。 4. 控制序列生成器的行为 除了基本的创建和使用操作之外,我们还可以通过ALTER TABLE语句来修改序列生成器的行为。比如,我们能够随心所欲地调整它的起步数值、每次增加的大小,还有极限值,甚至还能让它暂停工作或者重新启动序列生成器,就像控制家里的电灯开关一样轻松自如。下面是一些例子: sql -- 修改序列生成器的最大值 ALTER SEQUENCE my_sequence MAXVALUE 100; -- 启用序列生成器 ALTER SEQUENCE my_sequence START WITH 1; -- 禁用序列生成器 ALTER SEQUENCE my_sequence DISABLE; 以上代码将会分别修改my_sequence的最大值为100、将它的初始值设为1以及禁用它。敲黑板,注意啦!如果咱把序列生成器给关掉了,那可就意味着没法再用NEXTVAL函数去捞新的数字了,除非咱先把它重新打开。 5. 总结 总的来说,PostgreSQL中的序列生成器是一个非常有用的工具,可以帮助我们自动生成唯一的数字序列。通过正确的配置和使用,我们可以确保我们的应用程序始终保持数据的一致性和完整性。当然啦,这只是冰山一角的应用实例,实际上序列生成器这家伙肚子里还藏着不少酷炫好玩的功能嘞,就等着我们去一一解锁发现呢!如果你想更深入地了解PostgreSQL,不妨尝试自己动手创建一些序列生成器,看看它们能为你带来哪些惊喜吧!
2023-04-25 22:21:14
77
半夏微凉-t
Python
...码实现斐波那契数列的生成器 def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b 通过这段简短的生成器函数,我们就能轻松获取斐波那契数列的无限序列,这种简洁且强大的特性在我实习期间处理数据、编写脚本的过程中发挥了重要作用。 二、实习中期 深入Python实战项目 1. 数据清洗与分析 在实习过程中,我主要负责的一个项目是利用Python进行大规模数据清洗与初步分析。Pandas库成为了我的得力助手,其DataFrame对象极大地简化了对表格数据的操作。 python import pandas as pd 加载数据 df = pd.read_csv('data.csv') 数据清洗示例:处理缺失值 df.fillna(df.mean(), inplace=True) 数据分析示例:统计各列数据分布 df.describe() 这段代码展示了如何使用Pandas加载CSV文件,并对缺失值进行填充以及快速了解数据的基本统计信息。 2. Web后端开发 此外,我还尝试了Python在Web后端开发中的应用,Django框架为我打开了新的视角。下面是一个简单的视图函数示例: python from django.http import HttpResponse from .models import BlogPost def list_posts(request): posts = BlogPost.objects.all() return HttpResponse(f"Here are all the posts: {posts}") 这段代码展示了如何在Django中创建一个简单的视图函数,用于获取并返回所有博客文章。 三、实习反思与成长 在Python的实际运用中,我不断深化理解并体悟到编程不仅仅是写代码,更是一种解决问题的艺术。每次我碰到难题,像是性能瓶颈要优化啦,异常处理的棘手问题啦,这些都会让我特别来劲儿,忍不住深入地去琢磨Python这家伙的内在运行机制,就像在解剖一个精密的机械钟表一样,非得把它的里里外外都研究个透彻不可。 python 面对性能优化问题,我会尝试使用迭代器代替列表操作 def large_data_processing(data): for item in data: 进行高效的数据处理... pass 这段代码是为了说明,在处理大量数据时,合理利用Python的迭代器特性可以显著降低内存占用,提升程序运行效率。 总结这次实习经历,Python如同一位良师益友,陪伴我在实习路上不断试错、学习和成长。每一次手指在键盘上跳跃,每一次精心调试代码的过程,其实就像是在磨砺自己的知识宝剑,让它更加锋利和完善。这就是在日常点滴中,让咱的知识体系不断升级、日益精进的过程。未来这趟旅程还长着呢,但我打心底相信,有Python这位给力的小伙伴在手,甭管遇到啥样的挑战,我都敢拍胸脯保证,一定能够一往无前、无所畏惧地闯过去。
2023-09-07 13:41:24
323
晚秋落叶_
转载文章
...杀商品显示 1、使用生成器生成对应的表 记得在每个mapper类加入注解供spring扫描: @Repository 2、后端写得到秒杀商品的方法 ①、建实体类vo 用于连表查询,得到商品名字 package com.example.seckill.vo;import com.example.seckill.pojo.SeckillGoods;import lombok.Data;@Datapublic class SeckillGoodsVo extends SeckillGoods {private String goodsName;} ②、在SexkillGoodsMapper.xml文件中定义sql <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.seckill.mapper.SeckillGoodsMapper"><select id="queryAll" resultType="com.example.seckill.vo.SeckillGoodsVo">select sg.,g.goods_namefrom t_seckill_goods sg,t_goods gwhere sg.goods_id = g.gid;</select></mapper> ③、在mapper中定义 package com.example.seckill.mapper;import com.example.seckill.pojo.SeckillGoods;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.example.seckill.vo.SeckillGoodsVo;import org.springframework.stereotype.Repository;import java.util.List;/ <p> 秒杀商品信息表 Mapper 接口 </p> @author lv @since 2022-03-19/@Repositorypublic interface SeckillGoodsMapper extends BaseMapper<SeckillGoods> {List<SeckillGoodsVo> queryAll();} ④、service层与controller层 service: ISeckillGoodsService: package com.example.seckill.service;import com.example.seckill.pojo.SeckillGoods;import com.baomidou.mybatisplus.extension.service.IService;import com.example.seckill.util.response.ResponseResult;import com.example.seckill.vo.SeckillGoodsVo;import java.util.List;/ <p> 秒杀商品信息表 服务类 </p> @author lv @since 2022-03-19/public interface ISeckillGoodsService extends IService<SeckillGoods> {ResponseResult<List<SeckillGoodsVo>> queryAll();} SeckillGoodsServiceImpl: package com.example.seckill.service.impl;import com.example.seckill.pojo.SeckillGoods;import com.example.seckill.mapper.SeckillGoodsMapper;import com.example.seckill.service.ISeckillGoodsService;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.example.seckill.util.response.ResponseResult;import com.example.seckill.vo.SeckillGoodsVo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;/ <p> 秒杀商品信息表 服务实现类 </p> @author lv @since 2022-03-19/@Servicepublic class SeckillGoodsServiceImpl extends ServiceImpl<SeckillGoodsMapper, SeckillGoods> implements ISeckillGoodsService {@Autowiredprivate SeckillGoodsMapper seckillGoodsMapper;@Overridepublic ResponseResult<List<SeckillGoodsVo>> queryAll() {List<SeckillGoodsVo> list= seckillGoodsMapper.queryAll();return ResponseResult.success(list);} } controller: SeckillGoodsController: package com.example.seckill.controller;import com.example.seckill.service.ISeckillGoodsService;import com.example.seckill.util.response.ResponseResult;import com.example.seckill.vo.SeckillGoodsVo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.List;/ <p> 秒杀商品信息表 前端控制器 </p> @author lv @since 2022-03-19/@RestController@RequestMapping("/seckillGoods")public class SeckillGoodsController {@Autowiredprivate ISeckillGoodsService seckillGoodsService;@RequestMapping("/queryAll")public ResponseResult<List<SeckillGoodsVo>> queryAll(){return seckillGoodsService.queryAll();} } 得到秒杀商品数据: 3、前端显示数据 ①、编辑跳转秒杀界面 goodList.ftl: <!DOCTYPE html><html lang="en"><head><include "../common/head.ftl"><style>.layui-this{background: deepskyblue !important;}</style></head><body class="layui-container layui-bg-orange"><div class="layui-tab"><ul class="layui-tab-title"><li class="layui-this">普通商品</li><li>秒杀商品</li></ul><-- 普通商品--><div class="layui-tab-content"><div class="layui-tab-item layui-show"><div class="layui-form-item"><label class="layui-form-label">搜索栏</label><div class="layui-input-inline"><input type="text" id="normal_name" name="text" placeholder="请输入搜索内容" class="layui-input"></div><div class="layui-input-inline"><button class="layui-btn layui-btn-primary" id="normal_search">🔍</button><button class="layui-btn layui-btn-primary" id="normal_add">增加</button></div></div><table id="normal_goods" lay-filter="normal_goods"></table><script type="text/html" id="button_1"><a class="layui-btn layui-btn-xs" lay-event="normal_del">删除</a><a class="layui-btn layui-btn-xs" lay-event="normal_edit">编辑</a></script></div><--秒杀界面--><div class="layui-tab-item"><div class="layui-form-item"><label class="layui-form-label">搜索栏</label><div class="layui-input-inline"><input type="text" id="seckill_name" name="text" placeholder="请输入搜索内容" class="layui-input"></div><div class="layui-input-inline"><button class="layui-btn layui-btn-primary" id="seckill_search">🔍</button><button class="layui-btn layui-btn-primary" id="seckill_add">增加</button></div></div><table id="seckill_goods" lay-filter="seckill_goods"></table></div></div></div></div><--引入js--><script src="/static/asset/js/project/goodsList.js"></script></body></html> ②、获取数据 goodList.js: // 秒杀商品let seckill_table=table.render({elem: 'seckill_goods',height: 500,url: '/seckillGoods/queryAll' //数据接口,parseData(res){ //res 即为原始返回的数据return {"code": res.code===200?0:1, //解析接口状态"msg": res.message, //解析提示文本"count": res.total, //解析数据长度"data": res.data //解析数据列表};},cols: [[ //表头{field: 'id', title: '秒杀商品编号', width:80, sort: true},{field: 'goodsId', title: '商品名字id'},{field: 'seckillPrice', title: '秒杀价格'},{field: 'stockCount', title: '秒杀库存'},{field: 'startDate', title: '活动开始时间'},{field: 'endDate', title: '活动结束时间'},{field: 'goodsName', title: '商品名称'}]]}); 呈现界面: 二、秒杀商品添加 1、后端:接收前端添加秒杀商品的数据 ①、实体类vo:SeckillGoodsVo private List<Map<String,Object>> goods; 修改实体类时间的类型:SeckillGoods @ApiModelProperty("秒杀开始时间")@TableField("start_date")@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Timestamp startDate;@ApiModelProperty("秒杀结束时间")@TableField("end_date")@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Timestamp endDate; ②、mapper层:SeckillGoodsMapper int addGoods(SeckillGoodsVo seckillGoodsVo); ③、mapper.xml层:SeckillGoodsMapper 批量插入秒杀商品的sql语句: <insert id="addGoods">insert into t_seckill_goods(goods_id, seckill_price, stock_count, start_date, end_date)values<foreach collection="goods" item="g" separator=",">({g.gid},{g.goodsPrice},{g.goodsStock},{startDate},{endDate})</foreach></insert> ④、service层 ISeckillGoodsService: ResponseResult<List<SeckillGoodsVo>> addGoods(SeckillGoodsVo seckillGoodsVo); SeckillGoodsServiceImpl: @Overridepublic ResponseResult<List<SeckillGoodsVo>> addGoods(SeckillGoodsVo seckillGoodsVo) {int goods=seckillGoodsMapper.addGoods(seckillGoodsVo);return ResponseResult.success(goods);} ⑤、controller层 @RequestMapping("/add")public ResponseResult<List<SeckillGoodsVo>> add(@RequestBody SeckillGoodsVo seckillGoodsVo){return seckillGoodsService.addGoods(seckillGoodsVo);} 2、前端 ①、定义数据与刷新、添加 goodsList.js: var layer,row,seckill_table// 添加秒杀商品$("seckill_add").click(()=>{layer.open({type:2,content: '/goods/SeckillGoodsOperate',area: ['800px','600px']})})// 秒杀商品刷新var seckill_reload = ()=> {seckill_table.reload({page:{curr:1 //current} });} var layer,row,seckill_tablelayui.define(()=>{let table=layui.tablelayer=layui.layerlet $=layui.jquerylet normal_table=table.render({elem: 'normal_goods',height: 500,url: '/goods/queryAll' //数据接口,page: true //开启分页,parseData(res){ //res 即为原始返回的数据return {"code": res.code===200?0:1, //解析接口状态"msg": res.message, //解析提示文本"count": res.total, //解析数据长度"data": res.data //解析数据列表};},//用于对分页请求的参数:page、limit重新设定名称request: {pageName: 'page' //页码的参数名称,默认:page,limitName: 'rows' //每页数据量的参数名,默认:limit},cols: [[ //表头{field: 'gid', title: '商品编号', width:80, sort: true, fixed: 'left'},{field: 'goodsName', title: '商品名字'},{field: 'goodsTitle', title: '商品标题'},{field: 'goodsImg',title: '商品图片',width:200,templet: (goods) => <b onmouseover='showImg("${goods.goodsImg}",this)'> + goods.goodsImg + </b> },{field: 'goodsDetail', title: '商品详情'},{field: 'goodsPrice', title: '商品价格', sort: true},{field: 'goodsStock', title: '商品库存', sort: true},{field: 'operate', title: '商品操作',toolbar: 'button_1'}]]});// 刷新表格let reloadTable=()=>{let goodsName=$("normal_value").val()// 【JS】自动化渲染的重载,重载表格normal_table.reload({where: {//设定异步数据接口的额外参数,height: 300goodsName},page:{curr:1 //current} });}// 搜索$("normal_search").click(reloadTable)// 增加$("normal_add").click(()=>{row = nullopenDialog()})//工具条事件table.on('tool(normal_goods)', function(obj) { //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"let data = obj.data; //获得当前行数据let layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)let tr = obj.tr; //获得当前行 tr 的 DOM 对象(如果有的话)if (layEvent === 'normal_del') { //删除row = data//获得当前行的数据let url="/goods/del/"+data.gidlayer.confirm('确定删除吗?',{title:'删除'}, function(index){//向服务端发送删除指令og$.getJSON(url,{gid:data.gid}, function(ret){layer.close(index);//关闭弹窗reloadTable()});layer.close(index);//关闭弹窗});}if (layEvent === 'normal_edit') { //编辑row = dataopenDialog()} })// 页面弹出let openDialog=()=>{// 如果是iframe层layer.open({type: 2,content: '/goods/goodsOperate', //这里content是一个URL,如果你不想让iframe出现滚动条,你还可以content: ['http://sentsin.com', 'no']area:['800px','600px'],btn: ['确定','取消'],yes(index,layero){let url="/goods/insert"// 拿到表格数据let data=$(layero).find("iframe")[0].contentWindow.getFormData()if(row) {url="/goods/edit"}$.ajax({url,data,datatype: "json",success(res){layer.closeAll()reloadTable()layer.msg(res.message)} })} });}// -------------------------秒杀商品-------------------------------------------seckill_table=table.render({elem: 'seckill_goods',height: 500,url: '/seckillGoods/queryAll' //数据接口,parseData(res){ //res 即为原始返回的数据return {"code": res.code===200?0:1, //解析接口状态"msg": res.message, //解析提示文本"count": res.total, //解析数据长度"data": res.data //解析数据列表};},cols: [[ //表头{field: 'id', title: '秒杀商品编号', width:80, sort: true},{field: 'goodsId', title: '商品名字id'},{field: 'seckillPrice', title: '秒杀价格'},{field: 'stockCount', title: '秒杀库存'},{field: 'startDate', title: '活动开始时间'},{field: 'endDate', title: '活动结束时间'},{field: 'goodsName', title: '商品名称'}]]});// 添加秒杀商品$("seckill_add").click(()=>{layer.open({type:2,content: '/goods/SeckillGoodsOperate',area: ['800px','600px']})})})// 图片显示let showImg = (src,obj)=> {layer.tips(<img src="${src}" width="100px">, obj);}// 秒杀商品刷新var seckill_reload = ()=> {seckill_table.reload({page:{curr:1 //current} });} ②、增加秒杀商品弹出页面样式 <!DOCTYPE html><html lang="en"><head><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><link rel="stylesheet" href="/static/asset/js/layui/css/layui.css" media="all"></head><body><div style="padding:15px 0px;"><div class="layui-condition"><form id="fm" name="fm" action="/" method="post" class="layui-form"><div class="layui-form-item"><div class="layui-inline"><label class="layui-form-label" style="width: 100px;text-align: left;">秒杀活动时间:</label><div class="layui-input-inline" style="width:280px;"><input type="text" class="layui-input" id="dt"></div><div class="layui-input-inline"><button class="layui-btn" id="btn_save" type="button"><i class="fa fa-search fa-right"></i>保 存</button></div></div></div></form></div><div class="layui-fluid" style="margin-top:-18px;"><table id="tb_goods" class="layui-table" lay-filter="tb_goods" style="margin-top:-5px;"></table></div></div><script src="/static/asset/js/layui/layui.js"></script><script src="/static/asset/js/project/seckillGoodsOperate.js"></script></body></html> ③、实现增加秒杀商品 seckillGoodsOperate.js: layui.define(()=>{let table=layui.tablelet laydate = layui.laydatelet $=layui.jquerylet layer=layui.layer// 读取普通商品table.render({elem: 'tb_goods',height: 500,url: '/goods/queryAll' //数据接口,page: true //开启分页,parseData(res){ //res 即为原始返回的数据return {"code": res.code===200?0:1, //解析接口状态"msg": res.message, //解析提示文本"count": res.total, //解析数据长度"data": res.data //解析数据列表};},//用于对分页请求的参数:page、limit重新设定名称request: {pageName: 'page' //页码的参数名称,默认:page,limitName: 'rows' //每页数据量的参数名,默认:limit},cols: [[ //表头// 全选按钮{field: '', type:"checkbox"},{field: 'gid', title: '商品编号', width:80},{field: 'goodsName', title: '商品名字'},{field: 'goodsTitle', title: '商品标题'},{field: 'goodsDetail', title: '商品详情'},{field: 'goodsPrice', title: '商品价格', sort: true},{field: 'goodsStock', title: '商品库存', sort: true}]]});// 构建时间选择器//执行一个laydate实例laydate.render({elem: 'dt', //指定元素type: "datetime",range: "~"});$("btn_save").click(()=>{// 获取时间let val=$("dt").val()if(!val){layer.msg("请选择时间")return}// 解析时间2022-2-2 ~2022-5-2let startDate=new Date(val.split("~")[0]).getTime()let endDate=new Date(val.split("~")[1]).getTime()// 获得选中的普通商品,获取选中行的数据let rows= table.checkStatus('tb_goods').data; //idTest 即为基础参数 id 对应的值if(!rows||rows.length===0){layer.msg("请选择数据")return}layer.prompt(function(value, index, elem){// 修改每个商品的数量rows.forEach(e=>{e.goodsStock=value})let data={startDate,endDate,goods:rows}// 访问后台的秒杀商品的接口$.ajax({url: "/seckillGoods/add",contentType:'application/json',data: JSON.stringify(data),datatype:"json",//返回类型type:"post",success(res){parent.seckill_reload()layer.closeAll()parent.layer.closeAll()layer.msg(res.message)} })});})}) ④、展示结果 增加成功: 三、秒杀商品的操作 1、后端操作秒杀单个商品详情 ①、mapper层 SeckillGoodsMapper: Map<String,Object> querySeckillGoodsById(Long id); mapper.xml文件:SeckillGoodsMapper.xml <select id="querySeckillGoodsById" resultType="map">select sg.id,sg.goods_id,sg.seckill_price,sg.stock_count,sg.start_date,sg.end_date,g.goods_img,g.goods_title,g.goods_detail,g.goods_name,(casewhen current_timestamp < sg.start_date then 0when (current_timestamp between sg.start_date and sg.end_date) then 1when current_timestamp > sg.end_date then 2end) goods_statusfrom t_goods g,t_seckill_goods sgwhere g.gid = sg.goods_idand sg.id = {0}</select> ②、service层 ISeckillGoodsService: Map<String,Object> querySeckillGoodsById(Long id); SeckillGoodsServiceImpl: @Overridepublic Map<String, Object> querySeckillGoodsById(Long id) {return seckillGoodsMapper.querySeckillGoodsById(id);} ③、controller层:SeckillGoodsController package com.example.seckill.controller;import com.example.seckill.service.ISeckillGoodsService;import com.example.seckill.util.response.ResponseResult;import com.example.seckill.vo.SeckillGoodsVo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.;import org.springframework.web.servlet.ModelAndView;import java.util.List;/ <p> 秒杀商品信息表 前端控制器 </p> @author lv @since 2022-03-19/@Controller@RequestMapping("/seckillGoods")public class SeckillGoodsController {@Autowiredprivate ISeckillGoodsService seckillGoodsService;// 返回json@ResponseBody@RequestMapping("/queryAll")public ResponseResult<List<SeckillGoodsVo>> queryAll(){return seckillGoodsService.queryAll();}@ResponseBody@RequestMapping("/add")public ResponseResult<List<SeckillGoodsVo>> add(@RequestBody SeckillGoodsVo seckillGoodsVo){return seckillGoodsService.addGoods(seckillGoodsVo);}// 正常跳转界面@RequestMapping("/query/{id}")public ModelAndView querySeckillGoodsById(@PathVariable("id") Long id) {ModelAndView mv = new ModelAndView("/goods/goodsSeckill");mv.addObject("goods", seckillGoodsService.querySeckillGoodsById(id));return mv;} } 2、前端展示 ①、在goodsList.js增加列的操作 {field: '', title: '操作', width: 140,templet: function (d) {return <div><a class="layui-btn layui-btn-xs layui-btn-danger">删除</a><a href="/seckillGoods/query/${d.id}" class="layui-btn layui-btn-xs layui-btn-normal">秒杀</a></div>;} } ②、添加秒杀详情界面 :goodsSkill.ftl <!DOCTYPE html><html lang="en"><head><include "../common/head.ftl"/></head><body><table style="position: absolute;top:-10px;" class="layui-table" border="1" cellpadding="0" cellspacing="0"><tr><td style="width:120px;">商品图片</td><td><img src="${goods['goods_img']}" alt=""></td></tr><tr><td>商品名称</td><td>${goods['goods_name']}</td></tr><tr><td>商品标题</td><td>${goods['goods_title']}</td></tr><tr><td>商品价格</td><td>${goods['seckill_price']}</td></tr><tr><td>开始时间</td><td><div style="position: relative;${(goods['goods_status']==1)?string('top:10px;','')}">${goods['start_date']?string("yyyy-MM-dd HH:mm:ss")}-${goods['end_date']?string("yyyy-MM-dd HH:mm:ss")}<if goods['goods_status']==0>活动未开始<elseif goods['goods_status']==1>活动热卖中<div style="position:relative;top:-10px;float:right;"><input type="hidden" id="goodsId" value="${goods['goods_id']}" name="goodsId"/><button class="layui-btn" id="buy">立即抢购</button></div><else>活动已结束</if></div></td></tr></table><script src="/static/asset/js/project/goodsSeckill.js"></script></body></html> ③、实现:goodsSkill.js let layer, form, $;layui.define(() => {layer = layui.layerform = layui.form$ = layui.jquery$('buy').click(() => {$.ajax({url: '/seckillOrder/addOrder',data: {goodsId: $('goodsId').val()},dataType: 'json',type: 'post',async: false,success: function (rs) {if (rs.code === 200)layer.msg(rs.message)elselayer.msg(rs.message)} })});}) ④、展示效果 点击秒杀: 3、后端操作秒杀抢购功能 ①、导入雪花id工具包:SnowFlake package com.example.seckill.util;@SuppressWarnings("all")public class SnowFlake {/ 起始的时间戳/private final static long START_STMP = 1480166465631L;/ 每一部分占用的位数/private final static long SEQUENCE_BIT = 12; //序列号占用的位数private final static long MACHINE_BIT = 5; //机器标识占用的位数private final static long DATACENTER_BIT = 5;//数据中心占用的位数/ 每一部分的最大值/private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);/ 每一部分向左的位移/private final static long MACHINE_LEFT = SEQUENCE_BIT;private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;private long datacenterId; //数据中心private long machineId; //机器标识private long sequence = 0L; //序列号private long lastStmp = -1L;//上一次时间戳public SnowFlake(long datacenterId, long machineId) {if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");}if (machineId > MAX_MACHINE_NUM || machineId < 0) {throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");}this.datacenterId = datacenterId;this.machineId = machineId;}public static void main(String[] args) {SnowFlake snowFlake = new SnowFlake(2, 3);long start = System.currentTimeMillis();for (int i = 0; i < 1000000; i++) {System.out.println(snowFlake.nextId());}System.out.println(System.currentTimeMillis() - start);}/ 产生下一个ID @return/public synchronized long nextId() {long currStmp = getNewstmp();if (currStmp < lastStmp) {throw new RuntimeException("Clock moved backwards. Refusing to generate id");}if (currStmp == lastStmp) {//相同毫秒内,序列号自增sequence = (sequence + 1) & MAX_SEQUENCE;//同一毫秒的序列数已经达到最大if (sequence == 0L) {currStmp = getNextMill();} } else {//不同毫秒内,序列号置为0sequence = 0L;}lastStmp = currStmp;return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分| datacenterId << DATACENTER_LEFT //数据中心部分| machineId << MACHINE_LEFT //机器标识部分| sequence; //序列号部分}private long getNextMill() {long mill = getNewstmp();while (mill <= lastStmp) {mill = getNewstmp();}return mill;}private long getNewstmp() {return System.currentTimeMillis();} } ②、service层 ISeckillOrderService : package com.example.seckill.service;import com.example.seckill.pojo.SeckillOrder;import com.baomidou.mybatisplus.extension.service.IService;import com.example.seckill.pojo.User;import com.example.seckill.util.response.ResponseResult;/ <p> 秒杀订单信息表 服务类 </p> @author lv @since 2022-03-19/public interface ISeckillOrderService extends IService<SeckillOrder> {ResponseResult<?> addOrder(Long goodsId, User user);} SeckillOrderServiceImpl : package com.example.seckill.service.impl;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;import com.example.seckill.exception.BusinessException;import com.example.seckill.mapper.GoodsMapper;import com.example.seckill.mapper.OrderMapper;import com.example.seckill.mapper.SeckillGoodsMapper;import com.example.seckill.pojo.;import com.example.seckill.mapper.SeckillOrderMapper;import com.example.seckill.service.ISeckillOrderService;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.example.seckill.util.SnowFlake;import com.example.seckill.util.response.ResponseResult;import com.example.seckill.util.response.ResponseResultCode;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;/ <p> 秒杀订单信息表 服务实现类 </p> @author lv @since 2022-03-19/@Servicepublic class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrder> implements ISeckillOrderService {@Autowiredprivate SeckillGoodsMapper seckillGoodsMapper;@Autowiredprivate GoodsMapper goodsMapper;@Autowiredprivate OrderMapper orderMapper;@Transactional(rollbackFor = Exception.class)@Overridepublic ResponseResult<?> addOrder(Long goodsId, User user) {// 下单前判断库存数SeckillGoods goods = seckillGoodsMapper.selectOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goodsId));if (goods == null) {throw new BusinessException(ResponseResultCode.SECKILL_ORDER_ERROR);}if (goods.getStockCount() < 1) {throw new BusinessException(ResponseResultCode.SECKILL_ORDER_ERROR);}// 限购SeckillOrder one = this.getOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId()).eq("goods_id", goodsId));if (one != null) {throw new BusinessException(ResponseResultCode.SECKILL_ORDER_EXISTS_ERROR);}// 库存减一int i = seckillGoodsMapper.update(null, new UpdateWrapper<SeckillGoods>().eq("goods_id", goodsId).setSql("stock_count=stock_count-1"));// 根据商品编号查询对应的商品(拿名字)Goods goodsInfo = goodsMapper.selectOne(new QueryWrapper<Goods>().eq("gid", goodsId));// 生成订单//生成雪花idSnowFlake snowFlake = new SnowFlake(5, 9);long id = snowFlake.nextId();//生成对应的订单Order normalOrder = new Order();normalOrder.setOid(id);normalOrder.setUserId(user.getId());normalOrder.setGoodsId(goodsId);normalOrder.setGoodsName(goodsInfo.getGoodsName());normalOrder.setGoodsCount(1);normalOrder.setGoodsPrice(goods.getSeckillPrice());orderMapper.insert(normalOrder);//生成秒杀订单SeckillOrder seckillOrder = new SeckillOrder();seckillOrder.setUserId(user.getId());seckillOrder.setOrderId(normalOrder.getOid());seckillOrder.setGoodsId(goodsId);this.save(seckillOrder);return ResponseResult.success();} } ③、controller层 SeckillOrderController : package com.example.seckill.controller;import com.example.seckill.pojo.User;import com.example.seckill.service.ISeckillOrderService;import com.example.seckill.util.response.ResponseResult;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/ <p> 秒杀订单信息表 前端控制器 </p> @author lv @since 2022-03-19/@RestController@RequestMapping("/seckillOrder")public class SeckillOrderController {@Autowiredprivate ISeckillOrderService seckillOrderService;@RequestMapping("/addOrder")public ResponseResult<?> addOrder(Long goodsId, User user){return seckillOrderService.addOrder(goodsId,user);} } ④、呈现结果 限购次数: 本期内容结束,下期内容更完善!!!!!!!!!!!!!!!!!!!!!1 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_60389087/article/details/123601288。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-02-25 23:20:34
121
转载
Python
...洁高效。此外,对于大数据处理或科学计算场景,NumPy库提供的ndarray对象在性能上远超Python原生列表,可以实现快速的矩阵运算和统计分析。 近期,一篇发布于“Real Python”网站的文章深入探讨了如何利用列表推导式(List Comprehensions)和生成器表达式(Generator Expressions)对列表进行复杂操作,如过滤、映射和压缩数据,从而提升代码可读性和运行效率。文章还介绍了functools模块中的reduce函数,用于对列表元素执行累积操作,如求乘积、求序列中最长连续子序列等。 另外,在实际编程实践中,掌握列表的排序、切片、连接、复制等基本操作同样至关重要。例如,使用sorted()函数或列表的sort()方法对列表进行排序;利用切片技术实现列表的部分提取或替换;通过extend()和+运算符完成列表合并等。这些操作不仅能丰富你对Python列表的理解,更能在日常开发任务中助你事半功倍。 总的来说,深入学习和熟练运用Python列表的各种特性与功能,不仅有助于数据分析和处理,更能提升代码编写质量,使程序更加简洁、高效。同时,关注Python社区的最新动态和最佳实践,将能持续拓展你的编程技能边界,紧跟时代发展步伐。
2023-10-05 18:16:18
359
算法侠
转载文章
...回指定长度的斐波那契序列。 面向对象编程(OOP) , 面向对象编程是一种主流的程序设计范式,在Python中广泛使用。它通过将数据和操作数据的方法封装成“对象”来组织代码,强调重用和灵活性。在本文提到的斐波那契数列实现中,我们定义了一个名为Fibonacci的类,这是面向对象编程思想的具体应用,其中包含用于初始化数列的__init__方法以及获取数列特定长度的get方法。 动态规划 , 虽然文章中并未直接提及动态规划作为优化斐波那契数列生成的方式,但在实际编程中,动态规划是一种可以有效解决这类问题的技术。动态规划是一种通过将复杂问题分解为子问题,并存储和重用来避免重复计算的算法策略。如果要对文中斐波那契数列生成器进行优化,可以采用动态规划方法,只计算一次每个需要的斐波那契值,然后存储结果供后续计算使用,从而显著提升大范围或大规模斐波那契数列求解的效率。
2023-09-24 10:59:46
116
转载
HTML
...益的。例如,静态网站生成器(如Jekyll、Hugo和Hexo)正逐渐受到欢迎,它们不仅支持Markdown格式写作,还能结合HTML、CSS和JavaScript进行深度定制,极大地提升了博客制作效率与个性化程度。 近期,GitHub Pages与Netlify等服务平台提供了免费托管静态网站的服务,使得基于这些生成器创建个人博客变得更为便捷。用户只需将源代码推送到GitHub仓库,即可自动部署博客,实现版本控制的同时降低了运维成本。 此外,对于追求动态功能和交互体验的用户,可以考虑学习WordPress、Ghost等CMS系统来构建博客。它们基于数据库驱动,拥有丰富的主题模板和插件生态系统,使不具备专业编程技能的博主也能轻松管理内容和设计样式。 同时,随着Web技术的发展,响应式设计和无障碍访问已成为现代网页的标准配置。在创建个人博客时,确保你的HTML结构遵循语义化原则,配合CSS Flexbox或Grid布局,以及恰当运用ARIA属性提升辅助技术用户的体验,也是不容忽视的重要环节。 总之,在掌握了基础HTML编码后,持续关注并学习Web开发领域的最新趋势和技术,将有助于我们打造更专业、更具吸引力的个人博客空间。
2023-04-28 09:03:31
417
电脑达人
JSON
...了JSON作为轻量级数据交换格式的基础概念及其在JavaScript中的应用后,我们可进一步探索这一技术在现代Web开发及跨平台数据交互领域的最新动态与实践。 近年来,随着API经济的快速发展和微服务架构的广泛应用,JSON愈发成为主流的数据传输格式。例如,在GraphQL这一新兴的API查询语言中,JSON不仅被用作请求和响应的数据载体,还支持丰富的自定义类型系统,以满足日益复杂的应用场景需求。此外,诸如AJAX、RESTful API等技术也都深度依赖JSON进行前后端数据交互。 与此同时,考虑到性能优化和数据压缩的问题,业界也出现了对JSON的改进方案。比如,Facebook推出的Msgpack是一种二进制序列化格式,它在保持类似JSON语法简洁性的同时,显著提高了数据传输效率。另外,JSONB(Binary JSON)是PostgreSQL数据库为存储和检索JSON数据而提供的高效二进制格式。 不仅如此,针对JSON的安全性问题,开发者需关注如何有效验证和过滤JSON数据,防止注入攻击等安全风险。为此,一些库如ajv、 Joi等提供了严谨的数据模式验证功能,确保接收到的JSON数据符合预期结构和类型。 综上所述,深入理解和掌握JSON相关的最新技术和最佳实践,对于提升应用程序的数据处理能力、保障数据交互安全以及优化系统性能等方面具有重要价值。建议读者持续关注JSON及相关领域的发展趋势,并结合具体项目需求灵活运用各种解决方案。
2023-05-11 17:44:41
267
代码侠
Python
...结合。近日,一项关于序列生成算法的研究成果引起了业界关注。研究团队开发了一种基于深度学习的自动生成数列模型,该模型不仅能够生成正负交替数列,还能根据特定规则或模式生成更为复杂的数列结构。 例如,在数据压缩领域,有研究人员利用变种的正负交替编码策略优化了哈夫曼编码等算法,有效提高了数据压缩率和解压速度。此外,在高性能计算中,正负交替数列的性质被应用于负载均衡算法设计,以提升大规模并行计算任务的效率和稳定性。 对于初学者来说,理解Python中的迭代器协议和生成器表达式也是扩展数列生成知识的重要途径。通过运用生成器,可以实现更加高效且节省内存的无限数列生成方案,这对于处理大数据集或者进行数学分析具有实际意义。 同时,莫比乌斯函数作为数论中的经典概念,在密码学、图论等领域也有着广泛应用。在最新的科研进展中,就有学者尝试将莫比乌斯函数和其他数学工具结合,利用Python实现了一系列高级算法,用于解决复杂问题如素数分布预测、网络最大流最小割问题等。 总之,Python语言在数列生成上的灵活性及其与数学理论的紧密结合,为各个领域的研究与应用提供了强大支持。从基础的正负交替数列开始,逐步深入到更广泛的编程实践与理论探索,无疑将帮助我们更好地应对各类复杂计算挑战。
2023-01-27 13:46:53
343
电脑达人
PostgreSQL
在深入理解了PostgreSQL如何创建索引的基础知识后,我们可以进一步探索索引在实际应用中的最新趋势和优化策略。近期,PostgreSQL 14版本发布了一系列关于索引的增强功能,包括对BRIN(Block Range Indexes)索引类型的改进,它能更高效地处理大规模数据表,尤其对于按时间序列或连续数值排序的数据有显著提升。此外,还引入了表达式索引的新特性,允许用户基于列计算结果创建索引,极大地增强了索引的灵活性与适用性。 同时,在数据库优化实践中,了解何时以及如何选择正确的索引类型至关重要。例如,对于频繁进行范围查询的场景,B-tree索引可能是最佳选择;而对于全文搜索,则可能需要使用到gin或者gist索引。值得注意的是,尽管索引能够极大提升查询效率,但过度使用或不当使用也可能导致写操作性能下降及存储空间浪费,因此在设计数据库架构时需综合考量读写负载平衡及存储成本等因素。 此外,随着机器学习和AI技术的发展,智能化索引管理工具也逐渐崭露头角,它们可以根据历史查询模式自动推荐、调整甚至自动生成索引,以实现数据库性能的动态优化。这为数据库管理员提供了更为便捷高效的索引管理手段,有助于持续提升PostgreSQL等关系型数据库的服务质量和响应速度。
2023-11-16 14:06:06
485
晚秋落叶_t
Hadoop
一、引言 在大数据处理领域中,Hadoop是一个非常重要的工具。这个东西提供了一种超赞的分布式计算模式,能够帮我们轻轻松松地应对和处理那些海量数据,让管理起来不再头疼。不过呢,就像其他那些软件兄弟一样,Hadoop这家伙有时候也会闹点小情绪,其中一个常见的问题就是数据写入会重复发生。 在本文中,我们将深入探讨什么是数据写入重复,为什么会在Hadoop中发生,并提供几种解决这个问题的方法。这将包括详细的代码示例和解释。 二、什么是数据写入重复? 数据写入重复是指在一个数据库或其他存储系统中,同一个数据项被多次写入的情况。这可能会导致许多问题,例如: 1. 数据一致性问题 如果一个数据项被多次写入,那么它的最终状态可能并不明确。 2. 空间浪费 重复的数据会占用额外的空间,尤其是在大数据环境中,这可能会成为一个严重的问题。 3. 性能影响 当数据库或其他存储系统尝试处理大量重复的数据时,其性能可能会受到影响。 三、为什么会在Hadoop中发生数据写入重复? 在Hadoop中,数据写入重复通常发生在MapReduce任务中。这是因为MapReduce是个超级厉害的并行处理工具,它能够同时派出多个“小分队”去处理不同的数据块,就像是大家一起动手,各自负责一块儿,效率贼高。有时候,这些家伙可能会干出同样的活儿,然后把结果一股脑地塞进同一个文件里。 此外,数据写入重复也可能是由于其他原因引起的,例如错误的数据输入、网络故障等。 四、如何避免和解决数据写入重复? 以下是一些可以用来避免和解决数据写入重复的方法: 1. 使用ID生成器 当写入数据时,可以使用一个唯一的ID来标识每个数据项。这样就可以确保每个数据项只被写入一次。 python import uuid 生成唯一ID id = str(uuid.uuid4()) 2. 使用事务 在某些情况下,可以使用数据库事务来确保数据的一致性。这可以通过设置数据库的隔离级别来实现。 sql START TRANSACTION; INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2'); COMMIT; 3. 使用MapReduce的输出去重特性 Hadoop提供了MapReduce的输出去重特性,可以在Map阶段就去除重复的数据,然后再进行Reduce操作。 java public static class MyMapper extends Mapper { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] words = value.toString().split(" "); for (String word : words) { word = word.toLowerCase(); if (!word.isEmpty()) { context.write(new Text(word), one); } } } } 以上就是关于Hadoop中的数据写入重复的一些介绍和解决方案。希望对你有所帮助。
2023-05-18 08:48:57
506
秋水共长天一色-t
Golang
...库,如GORM(用于数据库操作)、Gin(Web框架)、Cobra(命令行工具生成器)等,这些库大大丰富了Golang的应用场景并提升了开发效率。与此同时,遵循良好的包设计原则,比如单一职责原则,也成为优秀Go程序员的重要素养之一。 综上所述,在Golang的世界里,库和包的概念不仅体现在语言设计层面,更是通过不断发展的生态系统和实践来展现其价值,值得广大开发者关注和深入研究。
2023-01-22 13:27:31
497
时光倒流-t
Logstash
...集、处理并解压缩各种数据,并将其发送到各种存储库中。虽然这玩意儿功能确实强大,可有时候吧,也会闹点小脾气。比如说,你可能会遇到“输出插件跟部分输出目标玩不来”的情况。 一、什么是Logstash? Logstash 是由 Elastic 公司开发的一款强大的日志收集、处理和分析工具。它能够把各种来源的数据,比如日志文件啦、数据库里的信息呀,甚至是网络流量那些乱七八糟的东西,一股脑儿地收集起来,集中到一个地方进行统一处理。接着呢,我们可以灵活运用 Logstash 那些超级实用的插件,对这些数据进行各种预处理操作,就比如筛选掉无用的信息、转换数据格式、解析复杂的数据结构等等。最后一步,就是把这些已经处理得妥妥当当的数据,发送到各种各样的目的地去,像是 Elasticsearch、Kafka、Solr 等等,就像快递小哥把包裹精准投递到各个收件人手中一样。 二、问题出现的原因 那么,为什么会出现"输出插件不支持所有输出目标"的问题呢?其实,这主要归咎于 Logstash 的架构设计。 在 Logstash 中,每个输入插件都会负责从源数据源获取数据,然后将这些数据传递给一个或多个中间插件(也称为管道),这些中间插件会根据需求对数据进行进一步处理。最后,这些经过处理的数据会被传递给输出插件,输出插件将数据发送到指定的目标。 虽然 Logstash 支持大量的输入、中间和输出插件,但是并不是所有的插件都能支持所有的输出目标。比如说,有些输出插件啊,它就有点“挑食”,只能把数据送到 Elasticsearch 或 Kafka 这两个特定的地方,而对于其他目的地,它们就爱莫能助了。这就解释了为啥我们偶尔会碰到“输出插件不支持所有输出目标”的问题啦。 三、如何解决这个问题? 要解决这个问题,我们通常需要找到一个能够支持我们所需输出目标的输出插件。幸运的是,Logstash 提供了大量的输出插件,几乎可以满足我们的所有需求。 如果我们找不到直接支持我们所需的输出目标的插件,那么我们也可以尝试使用一些通用的输出插件,例如 HTTP 插件。这个HTTP插件可厉害了,它能帮我们把数据送到任何兼容HTTP接口的地方去,这样一来,咱们就能随心所欲地定制数据发送的目的地啦! 以下是一个使用 HTTP 插件将数据发送到自定义 API 的示例: ruby input { generator { lines => ["Hello, World!"] } } filter { grok { match => [ "message", "%{GREEDYDATA:message}"] } } output { http { url => "http://example.com/api/v1/messages" method => "POST" body => "%{message}" } } 在这个示例中,我们首先使用一个生成器插件生成一条消息。然后,我们使用一个 Grok 插件来解析这条消息。最后,我们使用一个 HTTP 插件将这条消息发送到我们自定义的 API。 四、结论 总的来说,"输出插件不支持所有输出目标" 是一个常见的问题,但是只要我们选择了正确的输出插件,或者利用通用的输出插件自定义数据发送的目标,就能很好地解决这个问题。 在实际应用中,我们应该根据我们的具体需求来选择最合适的输出插件,同时也要注意及时更新 Logstash 的版本,以获取最新的插件和支持。 最后,我希望这篇文章能帮助你更好地理解和使用 Logstash,如果你有任何问题或建议,欢迎随时向我反馈。
2023-11-18 22:01:19
303
笑傲江湖-t
Hibernate
...着微服务架构的兴起,数据库操作的需求变得更为复杂且分散。传统的存储过程不再仅仅是单个应用程序的专属工具,而是开始在微服务环境中扮演重要角色。例如,Netflix在其Chaos Engineering实践中,就利用存储过程实现了服务间的断路和故障注入,以测试系统的弹性。同时,由于存储过程在数据库层面执行,减少了服务间通信的开销,符合微服务架构倡导的低延迟原则。 另一个趋势是使用云原生数据库,如AWS的RDS for PostgreSQL或Google Cloud的Cloud Spanner,这些数据库支持用户自定义存储过程,进一步增强了服务的可扩展性和定制性。在这些环境下,存储过程可以作为服务之间的API接口,提供统一的业务逻辑处理,简化服务之间的协作。 存储过程在数据治理和合规性方面也有所贡献。随着GDPR等数据保护法规的实施,存储过程可以用于执行数据清洗、脱敏等操作,确保数据处理过程透明且符合法规要求。 总的来说,存储过程在微服务架构中的角色正从传统的执行点扩展到服务间的交互、数据管理和合规性保障。开发者需要重新审视和学习如何在新的技术栈中有效地利用存储过程,以适应不断演进的软件开发环境。
2024-04-30 11:22:57
520
心灵驿站
Flink
...che Flink的数据源定义与处理,随着技术的不断发展和社区的持续贡献,更多高效实用的Source已经集成到Flink生态中。例如,2021年发布的Flink 1.13版本中,对Kafka 2.8.x新版本的支持得到显著增强,用户可以更加便捷地将Kafka作为实时流处理的数据源。同时,为了更好地满足云原生场景的需求,Flink也加强了与Amazon Kinesis、阿里云DataHub等云服务数据源的整合。 此外,在预处理阶段,Flink通过引入DataStream API的各类转换函数,使得数据清洗、过滤、聚合等操作更为灵活强大。而最新推出的Table & SQL API则进一步简化了批处理和流处理之间的界限,使得开发者能够以SQL的方式描述数据源,并进行复杂的数据转换与计算。 在实际应用案例方面,Netflix公开分享了如何借助Flink构建其大规模实时数据管道,从各种异构数据源收集数据并实时生成业务洞察。这一实践展示了Flink在数据源定义上的强大扩展性和在流处理领域的卓越性能。 综上所述,随着Apache Flink功能的不断完善以及行业应用的深入拓展,理解和掌握如何定义和优化数据源已经成为现代大数据工程师不可或缺的技能之一。对于希望深入了解Flink数据源特性的读者来说,除了官方文档外,还可以关注相关的技术博客、开源项目以及最新的学术研究成果,以便紧跟行业发展动态,提升自身技术水平。
2023-01-01 13:52:18
405
月影清风-t
PostgreSQL
如何在数据库中实现数据的分页和排序功能?——以PostgreSQL为例 1. 开场白 为什么我们需要分页和排序? 嘿,朋友们!今天我们要聊的是一个非常实用的话题:如何在PostgreSQL数据库中实现数据的分页和排序功能。这事儿每个搞数据库的小伙伴都可能碰到,不管是做那个让大伙儿用起来顺手的网页应用,还是搭建那个能搞定一大堆数据的分析平台,怎么把海量数据弄得清清楚楚、井井有条,真的是太关键了。 1.1 为什么需要分页? 想象一下,如果你正在开发一个电商网站,而你的产品目录里有成千上万种商品,如果直接把所有商品一次性展示给用户,不仅页面加载速度会慢得让人抓狂,而且用户也很难找到他们想要的商品。这时候,分页功能就显得尤为重要了。这家伙能帮我们把海量数据切成小块,吃起来方便,还能让咱们用得更爽,系统也跑得飞快! 1.2 为什么需要排序? 再来聊聊排序。在数据展示中,排序功能可以帮助用户根据自己的需求快速定位到所需信息。比如说,在新闻网站上,大家通常都想第一时间看到最新的新闻动态,或者是想找那些大家都爱看的热门文章,点开看看究竟多火。这样一来,我们就能按照用户的喜好来调整数据的排列顺序,让用户看着更舒心,自然也就更满意啦! 2. PostgreSQL中的分页与排序 既然了解了为什么我们需要这些功能,那么现在让我们来看看如何在PostgreSQL中实现它们吧! 2.1 分页的基本概念 在SQL中,分页通常涉及到两个关键参数:OFFSET 和 LIMIT。OFFSET用于指定从结果集的哪个位置开始返回数据,而LIMIT则限制了返回的数据条目数量。例如,如果你想从第5条记录开始获取10条数据,你可以这样写: sql SELECT FROM your_table_name ORDER BY some_column OFFSET 5 LIMIT 10; 这里,ORDER BY some_column是可选的,但强烈建议你总是为查询加上一个排序条件,因为没有明确的排序规则时,返回的数据可能会出现不一致的情况。 2.2 实战演练:分页查询实例 假设你有一个名为products的表,里面存储了各种产品的信息,你想实现一个分页功能来展示这些产品。首先,你得搞清楚用户现在要看的是哪一页(就是每页显示多少条记录),然后用这个信息算出正确的OFFSET值。这样子才能让用户的请求对上数据库里的数据。 sql -- 假设每页显示10条记录 WITH page AS ( SELECT product_id, name, price, ROW_NUMBER() OVER (ORDER BY product_id) AS row_number FROM products ) SELECT FROM page WHERE row_number BETWEEN (page_number - 1) items_per_page + 1 AND page_number items_per_page; 这里的page_number和items_per_page是根据前端传入的参数动态计算出来的。这样,无论用户请求的是第几页,你都可以正确地返回对应的数据。 2.3 排序的魅力 排序同样重要。通过在查询中添加ORDER BY子句,我们可以控制数据的输出顺序。比如,如果你想按价格降序排列产品列表,可以这样写: sql SELECT FROM products ORDER BY price DESC; 或者,如果你想让用户能够自由选择排序方式,可以在应用层接收用户的输入,并相应地调整SQL语句中的排序条件。 3. 结合分页与排序 实战案例 接下来,让我们将分页和排序结合起来,看看实际效果。咱们有个卖东西的网站,得弄个页面能让大伙儿按不同的标准(比如说价格高低、卖得快不快这些)来排产品。这样大家找东西就方便多了。 sql WITH sorted_products AS ( SELECT FROM products ORDER BY CASE WHEN :sort_by = 'price' THEN price END ASC, CASE WHEN :sort_by = 'sales' THEN sales END DESC ) SELECT FROM sorted_products LIMIT :items_per_page OFFSET (:page_number - 1) :items_per_page; 在这个例子中,:sort_by、:items_per_page和:page_number都是从用户输入或配置文件中获取的变量。这种方式使得我们的查询更加灵活,能够适应不同的业务场景。 4. 总结与反思 通过这篇文章,我们探索了如何在PostgreSQL中有效地实现数据的分页和排序功能。别看这些技术好像挺简单,其实它们对提升用户体验和让系统跑得更顺畅可重要着呢!当然啦,随着项目的不断推进,你可能会碰到更多棘手的问题,比如说要应对大量的同时访问,还得绞尽脑汁优化查询速度啥的。不过别担心,掌握了基础之后,一切都会变得容易起来。 希望这篇技术分享对你有所帮助,也欢迎你在评论区分享你的想法和经验。让我们一起进步,共同成长! --- 这就是我关于“如何在数据库中实现数据的分页和排序功能?”的全部内容啦!如果你对PostgreSQL或者其他数据库技术有任何疑问或见解,记得留言哦。编程路上,我们一起加油!
2024-10-17 16:29:27
53
晚秋落叶
Superset
...Superset中的数据可视化与数据可视化工具最新版本 引言:为什么Superset值得你关注? 嘿,大家好!今天我要和你们聊聊Superset——一个超级酷的数据可视化工具。如果你对数据分析或数据可视化超感兴趣,那你可得好好留意这个超级神器了!Superset不仅提供了强大的数据探索功能,还支持多种数据源,最重要的是它有一个非常活跃的社区,这意味着你可以得到很多帮助和支持。在这篇文章里,我带你一起探索Superset的新版本,教你如何用它制作超赞的数据可视化图表,让你的数据讲故事的能力瞬间提升! 一、Superset是什么?它为什么重要? 1.1 Superset简介 Superset是Apache软件基金会的一个开源项目,最初由Airbnb开发并捐赠给Apache基金会。这简直就是个现代版的数据探险神器,能让你轻松对接各种数据源,还能做出超炫的互动图表和报告,简直酷毙了!无论你是数据分析师还是产品经理,Superset都能帮助你更好地理解和展示数据。 1.2 Superset的重要性 在当今这个数据驱动的世界里,数据可视化变得越来越重要。这玩意儿不仅能帮我们迅速看出数据里的门道和规律,还能让我们说得明明白白,别人一听就懂。而Superset正是这样一个工具,它让数据可视化变得更加简单和高效。不管是做仪表板、出报告,还是搞深度数据分析,Superset都能给你很大的帮助。 二、Superset的主要功能和特点 2.1 数据连接与管理 首先,Superset允许用户连接到多种不同的数据源,包括关系型数据库(如MySQL、PostgreSQL)、NoSQL数据库(如MongoDB)、甚至是云服务(如Amazon Redshift)。有了这些连接,你就可以超级方便地从各种地方抓取数据,然后在Superset里轻松搞定管理和操作啦! 2.2 可视化选项丰富多样 Superset内置了大量的可视化类型,从常见的柱状图、折线图到地图、热力图等,应有尽有。不仅如此,你还能自己调整图表的外观和排版,想怎么整就怎么整,做出专属于你的独特图表! 2.3 交互式仪表板 另一个亮点是Superset的交互式仪表板功能。你可以把好几个图表拼在一起,做成一个超级炫酷的仪表板。这样一来,用户就能随心所欲地调整和查看他们想看的数据了。就像是自己动手组装了一个数据游乐场一样!这种灵活性对于实时监控业务指标或呈现复杂的数据关系非常有用。 2.4 高级分析功能 除了基础的可视化之外,Superset还提供了一些高级分析功能,比如预测分析、聚类分析等。这些功能可以帮助你挖掘数据中的深层次信息,发现潜在的机会或问题。 三、如何安装和配置Superset? 3.1 安装Superset 安装Superset其实并不难,但需要一些基本的Python环境知识。首先,你需要确保你的机器上已经安装了Python和pip。接下来,你可以通过以下命令来安装Superset: bash pip install superset 然后,运行以下命令初始化数据库: bash superset db upgrade 最后,创建一个管理员账户以便登录: bash superset fab create-admin \ --username admin \ --firstname Superset \ --lastname Admin \ --email admin@fab.org \ --password admin 启动Superset服务器: bash superset runserver 3.2 配置数据源 一旦你成功安装了Superset,就可以开始配置数据源了。如果你想连上那个MySQL数据库,就得先在Superset里新建个数据库连接。具体步骤如下: 1. 登录到Superset的Web界面。 2. 导航到“Sources” -> “Databases”。 3. 点击“Add Database”按钮。 4. 填写数据库的相关信息,比如主机名、端口号、数据库名称等。 5. 保存配置后,你就可以在Superset中使用这个数据源了。 四、实战案例 使用Superset进行数据可视化 4.1 创建一个简单的柱状图 假设你已经成功配置了一个数据源,现在让我们来创建一个简单的柱状图吧。首先,导航到“Explore”页面,选择你想要使用的数据集。接着,在“Visualization Type”下拉菜单中选择“Bar Chart”。 在接下来的步骤中,你可以根据自己的需求调整图表的各种属性,比如X轴和Y轴的数据字段、颜色方案、标签显示方式等。完成后,点击“Save as Dashboard”按钮将其添加到仪表板中。 4.2 制作一个动态仪表板 为了展示Superset的强大之处,让我们尝试创建一个更加复杂的仪表板。假设我们要监控一家电商公司的销售情况,可以按照以下步骤来制作: 1. 添加销售总额图表 选择一个时间序列数据集,创建一个折线图来展示销售额的变化趋势。 2. 加入产品类别占比 使用饼图来显示不同类别产品的销售占比。 3. 实时监控库存 创建一个条形图来展示当前各仓库的库存量。 4. 用户行为分析 添加一个表格来列出最近几天内活跃用户的详细信息。 完成上述步骤后,你就得到了一个全面且直观的销售监控仪表板。有了这个仪表板,你就能随时了解公司的情况,做出快速的决定啦! 五、总结与展望 经过一番探索,我相信大家都已经被Superset的魅力所吸引了吧?作为一款开源的数据可视化工具,它不仅功能强大、易用性强,而且拥有广泛的社区支持。无论你是想快速生成报告,还是深入分析数据,Superset都能满足你的需求。 当然,随着技术的发展,Superset也在不断地更新和完善。未来的日子,我们会看到更多酷炫的新功能被加入进来,让数据可视化变得更简单好玩儿!所以,赶紧试试看吧!相信Superset会给你带来意想不到的惊喜! --- 这就是我今天分享的内容啦,希望大家喜欢。如果你有任何问题或想法,欢迎留言讨论哦!
2024-12-15 16:30:11
90
红尘漫步
PostgreSQL
PostgreSQL 数据恢复后无法正常启动:排查指南 1. 前言 嗨,各位小伙伴!今天我们要聊的是一个让人头疼的问题——数据恢复后,PostgreSQL竟然无法正常启动。这就跟玩一款神秘的冒险游戏似的,每走一步都是全新的未知和挑战,真是太刺激了!不过别担心,我来带你一起探索这个谜题,看看如何一步步解决它。 2. 初步检查 日志文件 首先,让我们从最基本的开始。日志文件是我们排查问题的第一站。去你PostgreSQL安装目录里的log文件夹瞧一眼(一般在/var/log/postgresql/或者你自己设定的路径),找到最新生成的那个日志文件,比如说叫postgresql-YYYY-MM-DD.log。 代码示例: bash 在Linux系统上,查看最新日志文件 cat /var/log/postgresql/postgresql-$(date +%Y-%m-%d).log 日志文件中通常会包含一些关键信息,比如启动失败的原因、错误代码等。这些信息就像是一把钥匙,能够帮助我们解锁问题的真相。 3. 检查配置文件 接下来,我们需要检查一下postgresql.conf和pg_hba.conf这两个配置文件。它们就像是数据库的大脑和神经系统,控制着数据库的方方面面。 3.1 postgresql.conf 这个文件包含了数据库的各种配置参数。如果你之前动过一些手脚,或者在恢复的时候不小心改了啥,可能就会启动不了了。你可以用文本编辑器打开它,比如用vim: 代码示例: bash vim /etc/postgresql/12/main/postgresql.conf 仔细检查是否有明显的语法错误,比如拼写错误或者多余的逗号。另外,也要注意一些关键参数,比如data_directory是否指向正确的数据目录。 3.2 pg_hba.conf 这个文件控制着用户认证方式。如果恢复过程中用户认证方式发生了变化,也可能导致启动失败。 代码示例: bash vim /etc/postgresql/12/main/pg_hba.conf 确保配置正确,比如: plaintext IPv4 local connections: host all all 127.0.0.1/32 md5 4. 数据库文件损坏 有时候,数据恢复过程中可能会导致某些文件损坏,比如PG_VERSION文件。这个文件里写着数据库的版本号呢,要是版本号对不上,PostgreSQL可就启动不了啦。 代码示例: bash 检查PG_VERSION文件 cat /var/lib/postgresql/12/main/PG_VERSION 如果发现文件损坏,你可能需要重新初始化数据库集群。但是要注意,这将清除所有数据,所以一定要备份好重要的数据。 代码示例: bash sudo pg_dropcluster --stop 12 main sudo pg_createcluster --start -e UTF-8 12 main 5. 使用pg_resetwal工具 如果以上方法都不奏效,我们可以尝试使用pg_resetwal工具来重置WAL日志。这个工具可以修复一些常见的启动问题,但同样也会丢失一些未提交的数据。 代码示例: bash sudo pg_resetwal -D /var/lib/postgresql/12/main 请注意,这个操作风险较高,一定要确保已经备份了所有重要数据。 6. 最后的求助 社区和官方文档 如果你还是束手无策,不妨向社区求助。Stack Overflow、GitHub Issues、PostgreSQL邮件列表都是很好的资源。当然,官方文档也是必不可少的参考材料。 代码示例: bash 查看官方文档 https://www.postgresql.org/docs/ 7. 总结 通过以上的步骤,我们应该能够找到并解决PostgreSQL启动失败的问题。虽然过程可能有些曲折,但每一次的尝试都是一次宝贵的学习机会。希望你能顺利解决问题,继续享受PostgreSQL带来的乐趣! 希望这篇指南能对你有所帮助,如果有任何问题或需要进一步的帮助,欢迎随时联系我。加油,我们一起解决问题!
2024-12-24 15:53:32
110
凌波微步_
PostgreSQL
...题通常发生在处理大量数据或者长时间运行的系统中。 什么是PostgreSQL? PostgreSQL是一款强大的开源关系型数据库管理系统(RDBMS)。这个家伙能够应对各种刁钻复杂的查询,而且它的内功深厚,对数据完整性检查那是一把好手,存储能力也是杠杠的,绝对能给你稳稳的安全感。然而,你知道吗,就像其他那些软件一样,PostgreSQL这小家伙有时候也会闹点小脾气,比如可能会出现系统日志文件长得像个大胖子,或者直接耍起小性子、拒绝写入新内容的情况。 系统日志文件过大或无法写入的原因 系统日志文件过大通常是由于以下原因: 1. 日志级别设置过高 如果日志级别被设置为DEBUG或TRACE,那么每次执行操作时都会生成一条日志记录,这将迅速增加日志文件的大小。 2. 没有定期清理旧的日志文件 如果没有定期删除旧的日志文件,新的日志记录就会不断地追加到现有的日志文件中,使得日志文件越来越大。 3. 数据库服务器内存不足 如果数据库服务器的内存不足,那么操作系统可能会选择将部分数据写入磁盘而不是内存,这就可能导致日志文件增大。 系统日志文件无法写入通常是由于以下原因: 1. 磁盘空间不足 如果磁盘空间不足,那么新的日志记录将无法被写入磁盘,从而导致无法写入日志文件。 2. 文件权限错误 如果系统的用户没有足够的权限来写入日志文件,那么也无法写入日志文件。 3. 文件系统错误 如果文件系统出现错误,那么也可能会导致无法写入日志文件。 如何解决系统日志文件过大或无法写入的问题 解决系统日志文件过大的问题 要解决系统日志文件过大的问题,我们可以采取以下步骤: 1. 降低日志级别 我们可以通过修改配置文件来降低日志级别,只记录重要的日志信息,减少不必要的日志记录。 2. 定期清理旧的日志文件 我们可以编写脚本,定期删除旧的日志文件,释放磁盘空间。 3. 增加数据库服务器的内存 如果可能的话,我们可以增加数据库服务器的内存,以便能够更好地管理日志文件。 以下是一个使用PostgreSQL的示例代码,用于降低日志级别: sql ALTER LOGGING lc_messages TO WARNING; 以上命令会将日志级别从DEBUG降低到WARNING,这意味着只有在发生重要错误或警告时才会生成日志记录。 以下是一个使用PostgreSQL的示例代码,用于删除旧的日志文件: bash !/bin/bash 获取当前日期 today=$(date +%Y%m%d) 删除所有昨天及以前的日志文件 find /var/log/postgresql/ -type f -name "postgresql-.log" -mtime +1 -exec rm {} \; 以上脚本会在每天凌晨执行一次,查找并删除所有的昨天及以前的日志文件。 解决系统日志文件无法写入的问题 要解决系统日志文件无法写入的问题,我们可以采取以下步骤: 1. 增加磁盘空间 我们需要确保有足够的磁盘空间来保存日志文件。 2. 更改文件权限 我们需要确保系统的用户有足够的权限来写入日志文件。 3. 检查和修复文件系统 我们需要检查和修复文件系统中的错误。 以下是一个使用PostgreSQL的示例代码,用于检查和修复文件系统: bash sudo fsck -y / 以上命令会检查根目录下的文件系统,并尝试修复任何发现的错误。 结论 总的来说,系统日志文件过大或无法写入是一个常见的问题,但是只要我们采取适当的措施,就可以很容易地解决这个问题。咱们得养成定期检查系统日志文件的习惯,这样一来,一旦有啥小状况冒出来,咱们就能第一时间发现,及时对症下药,拿出应对措施。同时呢,咱们也得留个心眼儿,好好保护咱的系统日志文件,别一不留神手滑给删了,或者因为其他啥情况把那些重要的日志记录给弄丢喽。
2023-02-17 15:52:19
231
凌波微步_t
PostgreSQL
PostgreSQL系统配置错误:导致性能下降与故障发生的深层解析 1. 引言 PostgreSQL,作为一款功能强大、开源的关系型数据库管理系统,在全球范围内广受赞誉。不过呢,就像老话说的,“好马得配好鞍”,哪怕PostgreSQL这匹“骏马”有着超凡的性能和稳如磐石的稳定性,可一旦咱们给它配上不合适的“鞍子”,也就是配置出岔子或者系统闹点儿小情绪,那很可能就拖了它的后腿,影响性能,严重点儿还可能引发各种意想不到的问题。这篇文章咱们要接地气地聊聊,配置出岔子可能会带来的那些糟心影响,并且我还会手把手地带你瞧瞧实例代码,教你如何把配置调校得恰到好处,让这些问题通通远离咱们。 2. 配置失误对性能的影响 2.1 shared_buffers设置不合理 shared_buffers是PostgreSQL用于缓存数据的重要参数,其大小直接影响到数据库的查询性能。要是你把这数值设得过小,就等于是在让磁盘I/O忙个不停,频繁操作起来,就像个永不停歇的陀螺,会拖累整体性能,让系统跑得像只乌龟。反过来,如果你一不留神把数值调得过大,那就像是在内存里开辟了一大片空地却闲置不用,这就白白浪费了宝贵的内存资源,还会把其他系统进程挤得没地方住,人家也会闹情绪的。 postgresql -- 在postgresql.conf中调整shared_buffers值 shared_buffers = 4GB -- 假设服务器有足够内存支持此设置 2.2 work_mem不足 work_mem定义了每个SQL查询可以使用的内存量,对于复杂的排序、哈希操作等至关重要。过低的work_mem设定可能导致大量临时文件生成,进一步降低性能。 postgresql -- 调整work_mem大小 work_mem = 64MB -- 根据实际业务负载进行合理调整 3. 配置失误导致的故障案例 3.1 max_connections设置过高 max_connections参数限制了PostgreSQL同时接受的最大连接数。如果设置得过高,却没考虑服务器的实际承受能力,就像让一个普通人硬扛大铁锤,早晚得累垮。这样一来,系统资源就会被消耗殆尽,好比车票都被抢光了,新的连接请求就无法挤上这趟“网络列车”。最终,整个系统可能就要“罢工”瘫痪啦。 postgresql -- 不合理的高连接数设置示例 max_connections = 500 -- 若服务器硬件条件不足以支撑如此多的并发连接,则可能引发故障 3.2 日志设置不当造成磁盘空间耗尽 log_line_prefix、log_directory等日志相关参数设置不当,可能导致日志文件迅速增长,占用过多磁盘空间,进而引发数据库服务停止。 postgresql -- 错误的日志设置示例 log_line_prefix = '%t [%p]: ' -- 时间戳和进程ID前缀可能会使日志行变得冗长 log_directory = '/var/log/postgresql' -- 如果不加以定期清理,日志文件可能会撑满整个分区 4. 探讨与建议 面对PostgreSQL的系统配置问题,我们需要深入了解每个参数的含义以及它们在不同场景下的最佳实践。优化配置是一个持续的过程,需要结合业务特性和硬件资源来进行细致调优。 - 理解需求:首先,应了解业务特点,包括数据量大小、查询复杂度、并发访问量等因素。 - 监控分析:借助pg_stat_activity、pg_stat_bgwriter等视图监控数据库运行状态,结合如pgBadger、pg_top等工具分析性能瓶颈。 - 逐步调整:每次只更改一个参数,观察并评估效果,切忌盲目跟从网络上的推荐配置。 总结来说,PostgreSQL的强大性能背后,合理的配置是关键。要让咱们的数据库系统跑得溜又稳,像老黄牛一样可靠,给业务发展扎扎实实当好坚强后盾,那就必须把这些参数整得门儿清,调校得恰到好处才行。
2023-12-18 14:08:56
236
林中小径
转载文章
...tice公司及其收购数据库技术公司–StormDB的产品。Postgres-XL是一个横向扩展的开源数据库集群,具有足够的灵活性来处理不同的数据库任务。 Postgres-XL功能特性 开放源代码:(源协议使用宽松的“Mozilla Public License”许可,允许将开源代码与闭源代码混在一起使用。) 完全的ACID支持 可横向扩展的关系型数据库(RDBMS) 支持OLAP应用,采用MPP(Massively Parallel Processing:大规模并行处理系统)架构模式 支持OLTP应用,读写性能可扩展 集群级别的ACID特性 多租户安全 也可被用作分布式Key-Value存储 事务处理与数据分析处理混合型数据库 支持丰富的SQL语句类型,比如:关联子查询 支持绝大部分PostgreSQL的SQL语句 分布式多版本并发控制(MVCC:Multi-version Concurrency Control) 支持JSON和XML格式 Postgres-XL缺少的功能 内建的高可用机制 使用外部机制实现高可能,如:Corosync/Pacemaker 有未来功能提升的空间 增加节点/重新分片数据(re-shard)的简便性 数据重分布(redistribution)期间会锁表 可采用预分片(pre-shard)方式解决,在同台物理服务器上建立多个数据节点,每个节点存储一个数据分片。数据重分布时,将一些数据节点迁出即可 某些外键、唯一性约束功能 Postgres-XL架构 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-M9lFuEIP-1640133702200)(./assets/postgre-xl.jpg)] 基于开源项目Postgres-XC XL增加了MPP,允许数据节点间直接通讯,交换复杂跨节点关联查询相关数据信息,减少协调器负载。 多个协调器(Coordinator) 应用程序的数据库连入点 分析查询语句,生成执行计划 多个数据节点(DataNode) 实际的数据存储 数据自动打散分布到集群中各数据节点 本地执行查询 一个查询在所有相关节点上并行查询 全局事务管理器(GTM:Global Transaction Manager) 提供事务间一致性视图 部署GTM Proxy实例,以提高性能 Postgre-XL主要组件 GTM (Global Transaction Manager) - 全局事务管理器 GTM是Postgres-XL的一个关键组件,用于提供一致的事务管理和元组可见性控制。 GTM Standby GTM的备节点,在pgxc,pgxl中,GTM控制所有的全局事务分配,如果出现问题,就会导致整个集群不可用,为了增加可用性,增加该备用节点。当GTM出现问题时,GTM Standby可以升级为GTM,保证集群正常工作。 GTM-Proxy GTM需要与所有的Coordinators通信,为了降低压力,可以在每个Coordinator机器上部署一个GTM-Proxy。 Coordinator --协调器 协调器是应用程序到数据库的接口。它的作用类似于传统的PostgreSQL后台进程,但是协调器不存储任何实际数据。实际数据由数据节点存储。协调器接收SQL语句,根据需要获取全局事务Id和全局快照,确定涉及哪些数据节点,并要求它们执行(部分)语句。当向数据节点发出语句时,它与GXID和全局快照相关联,以便多版本并发控制(MVCC)属性扩展到集群范围。 Datanode --数据节点 用于实际存储数据。表可以分布在各个数据节点之间,也可以复制到所有数据节点。数据节点没有整个数据库的全局视图,它只负责本地存储的数据。接下来,协调器将检查传入语句,并制定子计划。然后,根据需要将这些数据连同GXID和全局快照一起传输到涉及的每个数据节点。数据节点可以在不同的会话中接收来自各个协调器的请求。但是,由于每个事务都是惟一标识的,并且与一致的(全局)快照相关联,所以每个数据节点都可以在其事务和快照上下文中正确执行。 Postgres-XL继承了PostgreSQL Postgres-XL是PostgreSQL的扩展并继承了其很多特性: 复杂查询 外键 触发器 视图 事务 MVCC(多版本控制) 此外,类似于PostgreSQL,用户可以通过多种方式扩展Postgres-XL,例如添加新的 数据类型 函数 操作 聚合函数 索引类型 过程语言 安装 环境说明 由于资源有限,gtm一台、另外两台身兼数职。 主机名 IP 角色 端口 nodename 数据目录 gtm 192.168.20.132 GTM 6666 gtm /nodes/gtm 协调器 5432 coord1 /nodes/coordinator xl1 192.168.20.133 数据节点 5433 node1 /nodes/pgdata gtm代理 6666 gtmpoxy01 /nodes/gtm_pxy1 协调器 5432 coord2 /nodes/coordinator xl2 192.168.20.134 数据节点 5433 node2 /nodes/pgdata gtm代理 6666 gtmpoxy02 /nodes/gtm_pxy2 要求 GNU make版本 3.8及以上版本 [root@pg ~] make --versionGNU Make 3.82Built for x86_64-redhat-linux-gnuCopyright (C) 2010 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law. 需安装GCC包 需安装tar包 用于解压缩文件 默认需要GNU Readline library 其作用是可以让psql命令行记住执行过的命令,并且可以通过键盘上下键切换命令。但是可以通过--without-readline禁用这个特性,或者可以指定--withlibedit-preferred选项来使用libedit 默认使用zlib压缩库 可通过--without-zlib选项来禁用 配置hosts 所有主机上都配置 [root@xl2 11] cat /etc/hosts127.0.0.1 localhost192.168.20.132 gtm192.168.20.133 xl1192.168.20.134 xl2 关闭防火墙、Selinux 所有主机都执行 关闭防火墙: [root@gtm ~] systemctl stop firewalld.service[root@gtm ~] systemctl disable firewalld.service selinux设置: [root@gtm ~]vim /etc/selinux/config 设置SELINUX=disabled,保存退出。 This file controls the state of SELinux on the system. SELINUX= can take one of these three values: enforcing - SELinux security policy is enforced. permissive - SELinux prints warnings instead of enforcing. disabled - No SELinux policy is loaded.SELINUX=disabled SELINUXTYPE= can take one of three two values: targeted - Targeted processes are protected, minimum - Modification of targeted policy. Only selected processes are protected. mls - Multi Level Security protection. 安装依赖包 所有主机上都执行 yum install -y flex bison readline-devel zlib-devel openjade docbook-style-dsssl gcc 创建用户 所有主机上都执行 [root@gtm ~] useradd postgres[root@gtm ~] passwd postgres[root@gtm ~] su - postgres[root@gtm ~] mkdir ~/.ssh[root@gtm ~] chmod 700 ~/.ssh 配置SSH免密登录 仅仅在gtm节点配置如下操作: [root@gtm ~] su - postgres[postgres@gtm ~] ssh-keygen -t rsa[postgres@gtm ~] cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys[postgres@gtm ~] chmod 600 ~/.ssh/authorized_keys 将刚生成的认证文件拷贝到xl1到xl2中,使得gtm节点可以免密码登录xl1~xl2的任意一个节点: [postgres@gtm ~] scp ~/.ssh/authorized_keys postgres@xl1:~/.ssh/[postgres@gtm ~] scp ~/.ssh/authorized_keys postgres@xl2:~/.ssh/ 对所有提示都不要输入,直接enter下一步。直到最后,因为第一次要求输入目标机器的用户密码,输入即可。 下载源码 下载地址:https://www.postgres-xl.org/download/ [root@slave ~] ll postgres-xl-10r1.1.tar.gz-rw-r--r-- 1 root root 28121666 May 30 05:21 postgres-xl-10r1.1.tar.gz 编译、安装Postgres-XL 所有节点都安装,编译需要一点时间,最好同时进行编译。 [root@slave ~] tar xvf postgres-xl-10r1.1.tar.gz[root@slave ~] ./configure --prefix=/home/postgres/pgxl/[root@slave ~] make[root@slave ~] make install[root@slave ~] cd contrib/ --安装必要的工具,在gtm节点上安装即可[root@slave ~] make[root@slave ~] make install 配置环境变量 所有节点都要配置 进入postgres用户,修改其环境变量,开始编辑 [root@gtm ~]su - postgres[postgres@gtm ~]vi .bashrc --不是.bash_profile 在打开的文件末尾,新增如下变量配置: export PGHOME=/home/postgres/pgxlexport LD_LIBRARY_PATH=$PGHOME/lib:$LD_LIBRARY_PATHexport PATH=$PGHOME/bin:$PATH 按住esc,然后输入:wq!保存退出。输入以下命令对更改重启生效。 [postgres@gtm ~] source .bashrc --不是.bash_profile 输入以下语句,如果输出变量结果,代表生效 [postgres@gtm ~] echo $PGHOME 应该输出/home/postgres/pgxl代表生效 配置集群 生成pgxc_ctl.conf配置文件 [postgres@gtm ~] pgxc_ctl prepare/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash.ERROR: File "/home/postgres/pgxl/pgxc_ctl/pgxc_ctl.conf" not found or not a regular file. No such file or directoryInstalling pgxc_ctl_bash script as /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxl/pgxc_ctl --configuration /home/postgres/pgxl/pgxc_ctl/pgxc_ctl.confFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxl/pgxc_ctl 配置pgxc_ctl.conf 新建/home/postgres/pgxc_ctl/pgxc_ctl.conf文件,编辑如下: 对着模板文件一个一个修改,否则会造成初始化过程出现各种神奇问题。 pgxcInstallDir=$PGHOMEpgxlDATA=$PGHOME/data pgxcOwner=postgres---- GTM Master -----------------------------------------gtmName=gtmgtmMasterServer=gtmgtmMasterPort=6666gtmMasterDir=$pgxlDATA/nodes/gtmgtmSlave=y Specify y if you configure GTM Slave. Otherwise, GTM slave will not be configured and all the following variables will be reset.gtmSlaveName=gtmSlavegtmSlaveServer=gtm value none means GTM slave is not available. Give none if you don't configure GTM Slave.gtmSlavePort=20001 Not used if you don't configure GTM slave.gtmSlaveDir=$pgxlDATA/nodes/gtmSlave Not used if you don't configure GTM slave.---- GTM-Proxy Master -------gtmProxyDir=$pgxlDATA/nodes/gtm_proxygtmProxy=y gtmProxyNames=(gtm_pxy1 gtm_pxy2) gtmProxyServers=(xl1 xl2) gtmProxyPorts=(6666 6666) gtmProxyDirs=($gtmProxyDir $gtmProxyDir) ---- Coordinators ---------coordMasterDir=$pgxlDATA/nodes/coordcoordNames=(coord1 coord2) coordPorts=(5432 5432) poolerPorts=(6667 6667) coordPgHbaEntries=(0.0.0.0/0)coordMasterServers=(xl1 xl2) coordMasterDirs=($coordMasterDir $coordMasterDir)coordMaxWALsernder=0 没设置备份节点,设置为0coordMaxWALSenders=($coordMaxWALsernder $coordMaxWALsernder) 数量保持和coordMasterServers一致coordSlave=n---- Datanodes ----------datanodeMasterDir=$pgxlDATA/nodes/dn_masterprimaryDatanode=xl1 主数据节点datanodeNames=(node1 node2)datanodePorts=(5433 5433) datanodePoolerPorts=(6668 6668) datanodePgHbaEntries=(0.0.0.0/0)datanodeMasterServers=(xl1 xl2)datanodeMasterDirs=($datanodeMasterDir $datanodeMasterDir)datanodeMaxWalSender=4datanodeMaxWALSenders=($datanodeMaxWalSender $datanodeMaxWalSender) 集群初始化,启动,停止 初始化 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all 输出结果: /bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlStopping all the coordinator masters.Stopping coordinator master coord1.Stopping coordinator master coord2.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existpg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord2" does not existDone.Stopping all the datanode masters.Stopping datanode master datanode1.Stopping datanode master datanode2.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.Stop GTM masterwaiting for server to shut down.... doneserver stopped[postgres@gtm ~]$ echo $PGHOME/home/postgres/pgxl[postgres@gtm ~]$ ll /home/postgres/pgxl/pgxc/nodes/gtm/gtm.^C[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlInitialize GTM masterERROR: target directory (/home/postgres/pgxc/nodes/gtm) exists and not empty. Skip GTM initilializationDone.Start GTM masterserver startingInitialize all the coordinator masters.Initialize coordinator master coord1.ERROR: target coordinator master coord1 is running now. Skip initilialization.Initialize coordinator master coord2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting coordinator master.Starting coordinator master coord1ERROR: target coordinator master coord1 is already running now. Skip initialization.Starting coordinator master coord22019-05-30 21:09:25.562 EDT [2148] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:09:25.562 EDT [2148] LOG: listening on IPv6 address "::", port 54322019-05-30 21:09:25.563 EDT [2148] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:09:25.601 EDT [2149] LOG: database system was shut down at 2019-05-30 21:09:22 EDT2019-05-30 21:09:25.605 EDT [2148] LOG: database system is ready to accept connections2019-05-30 21:09:25.612 EDT [2156] LOG: cluster monitor startedDone.Initialize all the datanode masters.Initialize the datanode master datanode1.Initialize the datanode master datanode2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting all the datanode masters.Starting datanode master datanode1.WARNING: datanode master datanode1 is running now. Skipping.Starting datanode master datanode2.2019-05-30 21:09:33.352 EDT [2404] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:09:33.352 EDT [2404] LOG: listening on IPv6 address "::", port 154322019-05-30 21:09:33.355 EDT [2404] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:09:33.392 EDT [2404] LOG: redirecting log output to logging collector process2019-05-30 21:09:33.392 EDT [2404] HINT: Future log output will appear in directory "pg_log".Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf stop all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlStopping all the coordinator masters.Stopping coordinator master coord1.Stopping coordinator master coord2.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existDone.Stopping all the datanode masters.Stopping datanode master datanode1.Stopping datanode master datanode2.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.Stop GTM masterwaiting for server to shut down.... doneserver stopped[postgres@gtm ~]$ pgxc_ctl/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlPGXC monitor allNot running: gtm masterRunning: coordinator master coord1Not running: coordinator master coord2Running: datanode master datanode1Not running: datanode master datanode2PGXC stop coordinator master coord1Stopping coordinator master coord1.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existDone.PGXC stop datanode master datanode1Stopping datanode master datanode1.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.PGXC monitor allNot running: gtm masterRunning: coordinator master coord1Not running: coordinator master coord2Running: datanode master datanode1Not running: datanode master datanode2PGXC monitor allNot running: gtm masterNot running: coordinator master coord1Not running: coordinator master coord2Not running: datanode master datanode1Not running: datanode master datanode2PGXC exit[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlInitialize GTM masterERROR: target directory (/home/postgres/pgxc/nodes/gtm) exists and not empty. Skip GTM initilializationDone.Start GTM masterserver startingInitialize all the coordinator masters.Initialize coordinator master coord1.Initialize coordinator master coord2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting coordinator master.Starting coordinator master coord1Starting coordinator master coord22019-05-30 21:13:03.998 EDT [25137] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:13:03.998 EDT [25137] LOG: listening on IPv6 address "::", port 54322019-05-30 21:13:04.000 EDT [25137] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:13:04.038 EDT [25138] LOG: database system was shut down at 2019-05-30 21:13:00 EDT2019-05-30 21:13:04.042 EDT [25137] LOG: database system is ready to accept connections2019-05-30 21:13:04.049 EDT [25145] LOG: cluster monitor started2019-05-30 21:13:04.020 EDT [2730] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:13:04.020 EDT [2730] LOG: listening on IPv6 address "::", port 54322019-05-30 21:13:04.021 EDT [2730] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:13:04.057 EDT [2731] LOG: database system was shut down at 2019-05-30 21:13:00 EDT2019-05-30 21:13:04.061 EDT [2730] LOG: database system is ready to accept connections2019-05-30 21:13:04.062 EDT [2738] LOG: cluster monitor startedDone.Initialize all the datanode masters.Initialize the datanode master datanode1.Initialize the datanode master datanode2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting all the datanode masters.Starting datanode master datanode1.Starting datanode master datanode2.2019-05-30 21:13:12.077 EDT [25392] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:13:12.077 EDT [25392] LOG: listening on IPv6 address "::", port 154322019-05-30 21:13:12.079 EDT [25392] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:13:12.114 EDT [25392] LOG: redirecting log output to logging collector process2019-05-30 21:13:12.114 EDT [25392] HINT: Future log output will appear in directory "pg_log".2019-05-30 21:13:12.079 EDT [2985] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:13:12.079 EDT [2985] LOG: listening on IPv6 address "::", port 154322019-05-30 21:13:12.081 EDT [2985] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:13:12.117 EDT [2985] LOG: redirecting log output to logging collector process2019-05-30 21:13:12.117 EDT [2985] HINT: Future log output will appear in directory "pg_log".Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done. 启动 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf start all 关闭 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf stop all 查看集群状态 [postgres@gtm ~]$ pgxc_ctl monitor all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlRunning: gtm masterRunning: coordinator master coord1Running: coordinator master coord2Running: datanode master datanode1Running: datanode master datanode2 配置集群信息 分别在数据节点、协调器节点上分别执行以下命令: 注:本节点只执行修改操作即可(alert node),其他节点执行创建命令(create node)。因为本节点已经包含本节点的信息。 create node coord1 with (type=coordinator,host=xl1, port=5432);create node coord2 with (type=coordinator,host=xl2, port=5432);alter node coord1 with (type=coordinator,host=xl1, port=5432);alter node coord2 with (type=coordinator,host=xl2, port=5432);create node datanode1 with (type=datanode, host=xl1,port=15432,primary=true,PREFERRED);create node datanode2 with (type=datanode, host=xl2,port=15432);alter node datanode1 with (type=datanode, host=xl1,port=15432,primary=true,PREFERRED);alter node datanode2 with (type=datanode, host=xl2,port=15432);select pgxc_pool_reload(); 分别登陆数据节点、协调器节点验证 postgres= select from pgxc_node;node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-----------+-----------+-----------+-----------+----------------+------------------+-------------coord1 | C | 5432 | xl1 | f | f | 1885696643coord2 | C | 5432 | xl2 | f | f | -1197102633datanode2 | D | 15432 | xl2 | f | f | -905831925datanode1 | D | 15432 | xl1 | t | f | 888802358(4 rows) 测试 插入数据 在数据节点1,执行相关操作。 通过协调器端口登录PG [postgres@xl1 ~]$ psql -p 5432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= create database lei;CREATE DATABASEpostgres= \c lei;You are now connected to database "lei" as user "postgres".lei= create table test1(id int,name text);CREATE TABLElei= insert into test1(id,name) select generate_series(1,8),'测试';INSERT 0 8lei= select from test1;id | name----+------1 | 测试2 | 测试5 | 测试6 | 测试8 | 测试3 | 测试4 | 测试7 | 测试(8 rows) 注:默认创建的表为分布式表,也就是每个数据节点值存储表的部分数据。关于表类型具体说明,下面有说明。 通过15432端口登录数据节点,查看数据 有5条数据 [postgres@xl1 ~]$ psql -p 15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= \c lei;You are now connected to database "lei" as user "postgres".lei= select from test1;id | name----+------1 | 测试2 | 测试5 | 测试6 | 测试8 | 测试(5 rows) 登录到节点2,查看数据 有3条数据 [postgres@xl2 ~]$ psql -p15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= \c lei;You are now connected to database "lei" as user "postgres".lei= select from test1;id | name----+------3 | 测试4 | 测试7 | 测试(3 rows) 两个节点的数据加起来整个8条,没有问题。 至此Postgre-XL集群搭建完成。 创建数据库、表时可能会出现以下错误: ERROR: Failed to get pooled connections 是因为pg_hba.conf配置不对,所有节点加上host all all 192.168.20.0/0 trust并重启集群即可。 ERROR: No Datanode defined in cluster 首先确认是否创建了数据节点,也就是create node相关的命令。如果创建了则执行select pgxc_pool_reload();使其生效即可。 集群管理与应用 表类型说明 REPLICATION表:各个datanode节点中,表的数据完全相同,也就是说,插入数据时,会分别在每个datanode节点插入相同数据。读数据时,只需要读任意一个datanode节点上的数据。 建表语法: CREATE TABLE repltab (col1 int, col2 int) DISTRIBUTE BY REPLICATION; DISTRIBUTE :会将插入的数据,按照拆分规则,分配到不同的datanode节点中存储,也就是sharding技术。每个datanode节点只保存了部分数据,通过coordinate节点可以查询完整的数据视图。 CREATE TABLE disttab(col1 int, col2 int, col3 text) DISTRIBUTE BY HASH(col1); 模拟数据插入 任意登录一个coordinate节点进行建表操作 [postgres@gtm ~]$ psql -h xl1 -p 5432 -U postgrespostgres= INSERT INTO disttab SELECT generate_series(1,100), generate_series(101, 200), 'foo';INSERT 0 100postgres= INSERT INTO repltab SELECT generate_series(1,100), generate_series(101, 200);INSERT 0 100 查看数据分布结果: DISTRIBUTE表分布结果 postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+-------1148549230 | 42-927910690 | 58(2 rows) REPLICATION表分布结果 postgres= SELECT count() FROM repltab;count -------100(1 row) 查看另一个datanode2中repltab表结果 [postgres@datanode2 pgxl9.5]$ psql -p 15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= SELECT count() FROM repltab;count -------100(1 row) 结论:REPLICATION表中,datanode1,datanode2中表是全部数据,一模一样。而DISTRIBUTE表,数据散落近乎平均分配到了datanode1,datanode2节点中。 新增数据节点与数据重分布 在线新增节点、并重新分布数据。 新增datanode节点 在gtm集群管理节点上执行pgxc_ctl命令 [postgres@gtm ~]$ pgxc_ctl/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.confFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlPGXC 在服务器xl3上,新增一个master角色的datanode节点,名称是datanode3 端口号暂定5430,pool master暂定6669 ,指定好数据目录位置,从两个节点升级到3个节点,之后要写3个none none应该是datanodeSpecificExtraConfig或者datanodeSpecificExtraPgHba配置PGXC add datanode master datanode3 xl3 15432 6671 /home/postgres/pgxc/nodes/datanode/datanode3 none none none 等待新增完成后,查询集群节点状态: postgres= select from pgxc_node;node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-----------+-----------+-----------+-----------+----------------+------------------+-------------datanode1 | D | 15432 | xl1 | t | f | 888802358datanode2 | D | 15432 | xl2 | f | f | -905831925datanode3 | D | 15432 | xl3 | f | f | -705831925coord1 | C | 5432 | xl1 | f | f | 1885696643coord2 | C | 5432 | xl2 | f | f | -1197102633(4 rows) 节点新增完毕 数据重新分布 由于新增节点后无法自动完成数据重新分布,需要手动操作。 DISTRIBUTE表分布在了node1,node2节点上,如下: postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+-------1148549230 | 42-927910690 | 58(2 rows) 新增一个节点后,将sharding表数据重新分配到三个节点上,将repl表复制到新节点 重分布sharding表postgres= ALTER TABLE disttab ADD NODE (datanode3);ALTER TABLE 复制数据到新节点postgres= ALTER TABLE repltab ADD NODE (datanode3);ALTER TABLE 查看新的数据分布: postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+--------700122826 | 36-927910690 | 321148549230 | 32(3 rows) 登录datanode3(新增的时候,放在了xl3服务器上,端口15432)节点查看数据: [postgres@gtm ~]$ psql -h xl3 -p 15432 -U postgrespsql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= select count() from repltab;count -------100(1 row) 很明显,通过 ALTER TABLE tt ADD NODE (dn)命令,可以将DISTRIBUTE表数据重新分布到新节点,重分布过程中会中断所有事务。可以将REPLICATION表数据复制到新节点。 从datanode节点中回收数据 postgres= ALTER TABLE disttab DELETE NODE (datanode3);ALTER TABLEpostgres= ALTER TABLE repltab DELETE NODE (datanode3);ALTER TABLE 删除数据节点 Postgresql-XL并没有检查将被删除的datanode节点是否有replicated/distributed表的数据,为了数据安全,在删除之前需要检查下被删除节点上的数据,有数据的话,要回收掉分配到其他节点,然后才能安全删除。删除数据节点分为四步骤: 1.查询要删除节点dn3的oid postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id -------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11819 | coord1 | C | 5432 | datanode1 | f | f | 188569664316384 | coord2 | C | 5432 | datanode2 | f | f | -119710263316385 | node1 | D | 5433 | datanode1 | f | t | 114854923016386 | node2 | D | 5433 | datanode2 | f | f | -92791069016397 | dn3 | D | 5430 | datanode1 | f | f | -700122826(5 rows) 2.查询dn3对应的oid中是否有数据 testdb= SELECT FROM pgxc_class WHERE nodeoids::integer[] @> ARRAY[16397];pcrelid | pclocatortype | pcattnum | pchashalgorithm | pchashbuckets | nodeoids ---------+---------------+----------+-----------------+---------------+-------------------16388 | H | 1 | 1 | 4096 | 16397 16385 1638616394 | R | 0 | 0 | 0 | 16397 16385 16386(2 rows) 3.有数据的先回收数据 postgres= ALTER TABLE disttab DELETE NODE (dn3);ALTER TABLEpostgres= ALTER TABLE repltab DELETE NODE (dn3);ALTER TABLEpostgres= SELECT FROM pgxc_class WHERE nodeoids::integer[] @> ARRAY[16397];pcrelid | pclocatortype | pcattnum | pchashalgorithm | pchashbuckets | nodeoids ---------+---------------+----------+-----------------+---------------+----------(0 rows) 4.安全删除dn3 PGXC$ remove datanode master dn3 clean 故障节点FAILOVER 1.查看当前集群状态 [postgres@gtm ~]$ psql -h xl1 -p 5432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11739 | coord1 | C | 5432 | xl1 | f | f | 188569664316384 | coord2 | C | 5432 | xl2 | f | f | -119710263316387 | datanode2 | D | 15432 | xl2 | f | f | -90583192516388 | datanode1 | D | 15432 | xl1 | t | t | 888802358(4 rows) 2.模拟datanode1节点故障 直接关闭即可 PGXC stop -m immediate datanode master datanode1Stopping datanode master datanode1.Done. 3.测试查询 只要查询涉及到datanode1上的数据,那么该查询就会报错 postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;WARNING: failed to receive file descriptors for connectionsERROR: Failed to get pooled connectionsHINT: This may happen because one or more nodes are currently unreachable, either because of node or network failure.Its also possible that the target node may have hit the connection limit or the pooler is configured with low connections.Please check if all nodes are running fine and also review max_connections and max_pool_size configuration parameterspostgres= SELECT xc_node_id, FROM disttab WHERE col1 = 3;xc_node_id | col1 | col2 | col3------------+------+------+-------905831925 | 3 | 103 | foo(1 row) 测试发现,查询范围如果涉及到故障的node1节点,会报错,而查询的数据范围不在node1上的话,仍然可以查询。 4.手动切换 要想切换,必须要提前配置slave节点。 PGXC$ failover datanode node1 切换完成后,查询集群 postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id -------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11819 | coord1 | C | 5432 | datanode1 | f | f | 188569664316384 | coord2 | C | 5432 | datanode2 | f | f | -119710263316386 | node2 | D | 15432 | datanode2 | f | f | -92791069016385 | node1 | D | 15433 | datanode2 | f | t | 1148549230(4 rows) 发现datanode1节点的ip和端口都已经替换为配置的slave了。 本篇文章为转载内容。原文链接:https://blog.csdn.net/qianglei6077/article/details/94379331。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-30 11:09:03
94
转载
Python
...能导致索引错误、丢失数据等问题。为解决此类问题,Python提供了多种方法,如使用列表推导式创建新列表代替原列表,或者先记录待删除项,遍历结束后再统一执行删除操作。此外,还可以考虑采用更为安全的数据结构,如集合或生成器表达式,在某些场景下能有效避免迭代过程中的状态改变问题。 另外,Python官方文档也强调了对于可变对象在循环中正确操作的重要性,并提供了一系列最佳实践建议。例如,《Effective Python》一书中提到,“在对容器元素进行迭代的同时对其进行修改是一种反模式,应尽量避免”。这一观点与我们之前分析“外星人入侵”游戏bug时得出的结论相吻合,再次提醒我们在实际编程中关注细节,遵循正确的编程范式,以提升代码质量和程序稳定性。
2023-12-10 11:15:11
201
昨夜星辰昨夜风_t
HTML
...出的HTML首页代码生成器这一创新工具后,我们进一步关注到电商和网页开发行业的最新动态。近期,多家大型电商平台纷纷推出自家的网页构建与设计工具,旨在赋能商家和开发者更高效地创建符合平台风格、用户体验优良的店铺页面。 例如,阿里巴巴旗下的淘宝也发布了“智能快建”服务,让商家通过拖拽式操作即可完成店铺装修,内置丰富的模板和组件满足各类营销场景需求。同时,该工具结合了AI技术,能够根据用户行为数据优化页面布局和内容推荐,有效提升转化率。 另外,亚马逊公司也不甘示弱,其Webstore Customization Toolkit允许第三方卖家定制自己的店面,提供一站式的商品展示、交易处理和数据分析功能。此工具简化了复杂的前端开发流程,使得没有专业编程背景的卖家也能轻松打造出专业级的线上商店。 深入解读这些举措,不难发现电商巨头们正致力于降低平台生态内商业活动的技术门槛,让更多企业和个人参与到数字经济的浪潮中来。而诸如HTML首页代码生成器这类工具的研发与应用,则是推动电商行业持续发展、创新用户体验的关键一环。在未来,我们期待看到更多便捷高效的网页制作工具涌现,以适应日益激烈的市场竞争与消费者对个性化体验的需求。
2023-07-22 15:59:38
372
数据库专家
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
clear 或 Ctrl+L
- 清除终端屏幕内容。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
2023-04-28
2023-08-09
2023-06-18
2023-04-14
2023-02-18
2023-04-17
2024-01-11
2023-10-03
2023-09-09
2023-06-13
2023-08-07
2023-03-11
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"