利他才能利己


  • 首页

  • 标签

  • 归档

  • 搜索

Ruby哈希中神奇的Symbol

发表于 2024-05-12 | 分类于 Ruby-on-Rails |

ruby 在 1.9.x 版本开始支持使用json方式创建哈希(Hash),示例代码如下:

1
2
3
4
5
6
7
8
# 1
user1 = {"name": 'Jhon', "age": 21}

# 2
user2 = {name: 'Jhon', age: 21}

# 3
user3 = {:name => 'Jhon', :age => 21}

#1 和 #2 中 user 的 Key(name 和 age)都默认是 Symbol 类型,而 #3 的 user 已经指定了 Key 类型是 Symbol。

而在 ruby 1.9.x 之前的版本不可以使用冒号:即类似#2方式语法创建,只能像下面这样创建 Hash:

1
2
3
user1 = {"name" => 'Jhon', "age" => 21}

user2 = {:name => 'Jhon', :age => 21}

可以看出 Symbol 一直都存在,并且在新版本得到了“重用”。

当然了,最新的 ruby 版本也支持 1.9.x 之前 Hash 创建方式:

1
user4 = {"name" => 'Jhon', "age" => 21}

这个创建 Hash 的方法,Key 是 String 类型而不是 Symbol 类型。

我现在用的是 ruby 2.7.x 版本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# frozen_string_literal: true

user1 = { "name": 'Jhon', "age": 21 }
user1.each_key do |key|
puts "user1 key 类型:#{key.class.to_s}"
end

puts("--------------------天生我材必有用--------------------")

user2 = { name: 'Jhon', age: 21 }
user2.each_key do |key|
puts "user2 key 类型:#{key.class.to_s}"
end

puts("-------------------不以物喜不以己悲-------------------")


user3 = { :name => 'Jhon', :age => 21 }
user3.each_key do |key|
puts "user3 key 类型:#{key.class.to_s}"
end

puts("--------------------桃花依旧笑春风--------------------")


user4 = { "name" => 'Jhon', "age" => 21 }
user4.each_key do |key|
puts "user4 key 类型:#{key.class.to_s}"
end

运行得到结果

user1 key 类型:Symbol
user1 key 类型:Symbol
——————–天生我材必有用——————–
user2 key 类型:Symbol
user2 key 类型:Symbol
——————-不以物喜不以己悲——————-
user3 key 类型:Symbol
user3 key 类型:Symbol
——————–桃花依旧笑春风——————–
user4 key 类型:String
user4 key 类型:String

看到这里,你可能会很疑惑:写这么多,你到底是遇到了什么问题?!

我们先做好情绪管理,书归正传。

情景是这样的,我要从数据库(MySQL)user 表中读取数据,将读取的数据实例化为 ruby 的 User 类。这里我没有采用任何 ORM 工具,纯手工打造。

ruby user.rb 代码片段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class User
# 使用 attr_accessor 自动生成 getter 和 setter 方法
attr_accessor :id, :phone, :avatar, :age, :motto, :created_at, :updated_at

# 构造器,用于创建 User 对象时初始化字段
def initialize(attributes = {})
@id = attributes[:id]
@phone = attributes[:phone]
@avatar = attributes[:avatar]
@age = attributes[:age]
@motto = attributes[:motto]
@created_at = attributes[:created_at]
@updated_at = attributes[:updated_at]
end
end

User 类的属性和数据库表 user 的字段保持一致。

db.ruby 代码片段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# frozen_string_literal: true

require 'mysql2'
require_relative '../model/user'

begin
# 配置数据库连接
client = Mysql2::Client.new(
host: 'localhost',
username: 'root',
password: "",
database: "db"
)

# 查询数据
result = client.query("select * from user where id=1")
result.each do |row|
puts "query form table #{row}"
end

user_record = result.first

# 根据查询结果构建User类
user = User.new(user_record)

puts "user phone is: #{user.phone}"

ensure
# 关闭连接
client.close if client
end

结果有点出乎意料,实例化的 user 各个属性居然为空。百思不得骑jie……

开始调试,我用的是 RubyMine 进行开发的,会让你安装 ruby-debug-ide、debase,直接安装就可以了。

真相就要大白了,我加个打印,各位看官就明白了。

1
2
3
4
user_record = result.first
user_record.each_key do |key|
puts "user_record key 类型: #{key.class.to_s}"
end

打印结果清一色是 String,而在 User 构造方法中的 Key 都是 Symbol 类型,明显类型不一致,所以实例化失败,导致 user 各个属性字段就为空了🤕。

解决方法很简单,从 MySQL 查询出来的 Hash 数据的 Key 类型(String)转换为 Symbol 即可,有两个常用的方法可以进行转换:

1
2
3
4
5
6
7
8
9
10
# 方法一:批量转换
user_hash = user_record.transform_keys(&:to_sym)

# 方法二:单独转换
user_hash = user_record.each_with_object({}) do |(column, value), hash|
hash[column.to_sym] = value
end

# 构建User类
user = User.new(user_hash)

至此,问题解决。


附上来自 AI 的解答:

使用 mysql2 查询 MySQL 数据库时,默认得到的哈希键是字符串类型,这是出于对不同数据库类型和查询结果灵活性的考虑。如果需要,您可以在处理查询结果时将这些字符串键转换为你需要的类型。


Ruby 是一门简单上手的编程语言,小巧可爱,有需要就去看看吧。顺便推一下自己的 Ruby on Rails 笔记:点此处直接飞往✈️。

docker容器中创建非root用户

发表于 2024-01-20 | 分类于 Server , Tools |

简介

用 docker 也有一段时间了,一直在 docker 容器中使用 root 用户肆意操作。直到部署 stable diffusion webui 我才发现无法使用 root 用户运行它,于是才幡然醒悟:是时候搞个非 root 用户了。

我使用的 docker 镜像文件是 centos:centos7.9.2009,使用如下命令就可以拉取其镜像文件。

1
docker pull centos:centos7.9.2009

接下来的内容都是基于该镜像进行操作的,仅供大家参考。

厉兵秣马

我们还是要做些准备工作。

1、创建/运行容器

1
2
docker run -d -it --name c_os centos:centos7.9.2009
docker container start c_os

2、进入容器(此时用的是 root 用户,docker默认如此)

1
docker exec -it c_os bash

3、安装相关工具

1
2
yum install -y vim
yum install -y sudo

万事俱备

做完上面的工作,我们就可以来操刀了。

跟着命令敲,都是基本操作。

1
2
3
4
5
# 添加 nuser 这个用户
useradd -d /home/nuser -m nuser

# 设置密码
passwd nuser

需要为该用户 nuser 设置一个密码,比如 565656。

1
usermod -aG wheel nuser

编辑 /etc/sudoers 文件

1
2
chmod u+w /etc/sudoers
vim /etc/sudoers

修改两个地方

1
2
3
4
5
## Allows people in group wheel to run all commands  
# 取消这个注释
wheel ALL=(ALL) ALL
# 新增
nuser ALL=(ALL) ALL

编辑完成之后,关闭文件的编辑权限。

1
chmod u-w /etc/sudoers

我们退出刚才进入的容器

1
exit

指定用户 nuser 重新进入容器

1
docker exec --user nuser -it c_os bash

可以使用如下命令查看当前登入的用户是哪位

1
whoami

结果显示:nuser,搞定!


手动降级openssl:解决-Rails-部署的问题

发表于 2024-01-15 | 分类于 Ruby-on-Rails |

简介

1、为什么要降 openssl 版本?

我的工程比较老,使用的还是 rails 3.2 、ruby 1.8(自己源码编译的),生产环境的应用服务器是 passenger。在安装 passenger时发生了错误(passenger-install-nginx-module 的安装方式):提示需要 ruby 支持 openssl。

1
2
3
4
5
6
ossl_pkey_ec.c:815: error: ‘EC_GROUP_new_curve_GF2m’ undeclared (first use in this function)
ossl_pkey_ec.c:815: error: (Each undeclared identifier is reported only once
ossl_pkey_ec.c:815: error: for each function it appears in.)
make[1]: *** [ossl_pkey_ec.o] Error 1
make[1]: Leaving directory `/home/vagrant/ruby-1.8.7-p357/ext/openssl'
make: *** [all] Error 1

后面我查询了下面两篇文章,折腾了很久未能解决问题,最后无奈降级系统自带的 openssl 版本。

  • https://www.cnblogs.com/grimm/p/5568129.html

  • ruby升级时编译报错EC_GROUP_new_curve_GF2m

当前云服务器的系统是 centOS 6.10,默认安装了 openssl 1.0.x 版本,我需要在 ruby-1.8 环境下使用 openssl 0.9.8 系列版本。

2、我还尝试编译 ruby 源码中自带的 openssl

1
2
cd ruby-1.8.7/ext/openssl
ruby extconf.rb

报错:

=== OpenSSL for Ruby configurator ===
=== Checking for system dependent stuff… ===
checking for t_open() in -lnsl… no
checking for socket() in -lsocket… no
checking for assert.h… yes
=== Checking for required stuff… ===
checking for openssl/ssl.h… no
=== Checking for required stuff failed. ===
Makefile wasn’t created. Fix the errors above.

系统自带的 openssl 版本(OpenSSL 1.0.1e-fips 11 Feb 2013)和 ruby 版本去编译 openssl 扩展库不兼容,无法通过编译。

可以通过下面命令查看 openssl 版本:

1
openssl version

下面我们正式进入战斗。

安装低版本 openssl

1、下载 openssl-0.9.8

1
2
3
4
cd /usr/local
wget https://www.openssl.org/source/openssl-0.9.8e.tar.gz --no-check-certificate
tar -zxvf openssl-0.9.8e.tar.gz
cd openssl-0.9.8e

2、编译

1
2
3
./config --prefix=/usr/local/ssl -fPIC no-asm
make
make install

正常情况下,我们配置一下默认安装路径即可,但是这里我们加了两个参数 -fPIC、 no-asm。

  • 用 no-asm 是为了解决类似 “md5-x86_64.s:41: Error: 0xd76aa478 out range of signed 32bit displacement” 的报错。

  • 用 -fPIC 是为了解决类似 “/usr/local/ssl/lib/libssl.a: error adding symbols: Bad value” 的报错。

如果你使用 ./config --prefix=/usr/local/ssl 能够编译、安装正常就不需要加这两个参数。如果报错了,请先执行 make clean 操作。

1
2
3
4
5
我们都知道在生成一个动态库时需要指定 -fPIC,这是创建动态库所要求的,共享库被加载是在内存中的位置是不固定的,是一个相对的位置。
那么在生成静态库时通常不指定 -fPIC, 可是在64bit编译使用静态库就会提示需要 -fPIC 重新编译该库。
由于 openssl 编译静态库时,没有使用 -fPIC 选项,使得编译出来的静态库没有重定位能力。
这样在 64bit 机器上编译出来的静态库如果不指定-fPIC选项几乎全部不能使用。
因此需要重新加上 -fPIC 从新编译 openssl。

编译如果报找不到库的错误,请安装 libssl

1
yum install libssl-dev

3、备份之前 OpenSSL 版本的文件,以方便恢复

1
2
mv -f /usr/bin/openssl /usr/bin/openssl.old
mv -f /usr/include/openssl /usr/include/openssl.old

4、增加软链,指向新版本的 OpenSSL 路径

1
2
ln -s /usr/local/ssl/bin/openssl /usr/bin/openssl
ln -s /usr/local/ssl/include/openssl /usr/include/openssl

5、写入 ld 配置文件ld.so.conf

1
echo "/usr/local/ssl/lib">>/etc/ld.so.conf

可以看下 vim /etc/ld.so.conf 文件内容。

6、添加 so 库的路径,添加完成之后,运行ldconfig,将新增的 so 文件缓存到/etc/ld.so.cache中。

1
ldconfig -v

最后,确认版本是否正确。

1
openssl version -a

OpenSSL 0.9.8e 23 Feb 2007
built on: Thu Jan 5 11:13:28 CST 2023
platform: linux-x86_64

检查一下,ruby 是否带 openssl 模块:

1
ruby -ropenssl -e 'puts OpenSSL::OPENSSL_VERSION'

理论上还不行,别着急,接下来我们重新编译 ruby。

编译 ruby+openssl

编译 ruby + openssl 模块:

1
2
3
4
5
6
7
8
9
10
cd /usr/local/ruby-1.8.7
# 我之前编译过
make clean

# --prefix 指定ruby安装目录
# --with-openssl-dir 指定openssl目录(刚安装的 openssl)
./configure --enable-pthread --prefix=/usr/local --with-openssl-dir=/usr/local/ssl

make
make install

(可选操作)如果还是编译报错,可以尝试用下面这种方式进行修复:

1
2
3
4
# ruby 源码自带了 openssl 库,当然还有其他扩展库如 zlib
cd /usr/local/ruby-1.8.7/ext/openssl
ruby extconf.rb
make && make install

编译完成之后,也是修复成功了。如果这一步你还是无法通过编译,先放弃这个操作,直接看下面的内容去检测一下。

检测一下编译后的 ruby 是否带 openssl 模块,使用如下命令。

1
2
3
4
5
6
# 检查 openssl zlib
ruby -ropenssl -rzlib -e "puts :success"

# 用下面的也可以
ruby -ropenssl -e "puts :success"
ruby -ropenssl -e 'puts OpenSSL::OPENSSL_VERSION'

在控制台会输出对应的信息就代表成功了。如果没有成功会报类似如下的错误:

ruby: no such file to load – openssl (LoadError)

上面能够成功,我也觉得很神奇,不管怎么样我遇到的问题算是解决了。后来我在 官网 doc 上面找到了一些解释。

module OpenSSL

OpenSSL (指的是 ruby 自带的 openssl) provides SSL, TLS and general purpose cryptography. It wraps the OpenSSL (指的是系统的 openssl 库) library.

Install

OpenSSL comes bundled with the Standard Library of Ruby.

This means the OpenSSL extension is compiled with Ruby and packaged on build. During compile time, Ruby will need to link against the OpenSSL library on your system. However, you cannot use openssl provided by Apple to build standard library openssl.

If you use OSX, you should install another openssl and run “./configure –with-openssl-dir=/path/to/another-openssl“. For Homebrew user, run brew install openssl and then “./configure –with-openssl-dir=brew –prefix openssl “.

最后,自己重新编译 passenger,工程可以正常运行了。


~~

当你遇到问题的时候,不要慌张,试着让自己放下问题出去走一走,回过头再来看或许问题就引刃而解了。

访问 Nginx 403 Fobidden

发表于 2023-01-07 | 分类于 Ruby-on-Rails |

简介

在 CentOS release 6.10 (Final) 部署了 Rails 应用,其中用到了 Passenger、Nginx,通过二者实现用户对 Rails 应用的访问。

在部署的过程中,遇到了一个较坑的问题,记录在此分享给有需要的人。

问题是这样的,部署完成后我开始进行测试,在浏览器打开 Rails 网站发现总是报 403 Forbidden 错误,最后发现问题出在 Passenger 身上。

Nginx 403

在 Rails 应用中出现 403(Forbidden) 错误,一般是有如下几个原因:

  1. 没有权限访问相关的资源;
  2. nginx 配置文件错误:
  • nginx 配置文件中,在 server 下配置了多余的 location ~
  • 端口错误
  • 没有开启 passenger(passenger_enabled on)
  • Passenger 没有配置或者配置错误(下面两个选项配置的文件地址不对)
1
2
passenger_root  
passenger_ruby

我最初怀疑就是因为权限问题导致的,然后使用 ls 也查看了 Rails 应用目录的权限,没有问题。差点就开始执行 chmod -R 777 了 😓。

我的 nginx 配置文件(截一部分)如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
http {
passenger_root /opt/passenger;
passenger_ruby /usr/local/bin/ruby;
passenger_ignore_client_abort on;
passenger_max_pool_size 80;
passenger_use_global_queue on;
passenger_user name;

server {
listen 8080;
server_name localhost;
root /var/rails_app/public;
passenger_enabled on;
}
}

随手写了一个 index.html,然后通过 nginx 去访问这个 index.html 文件。发现这个在网页上正常显示,访问权限是有的(无论是 IP 还是资源目录都有权限访问),并且 nginx 的配置文件也没有错误。

折腾一圈之后,并没有发现 nginx 有什么问题,顿时大脑嗡嗡的 😭

罪魁祸首

既然 nginx 大兄弟没有问题,那就是 Passenger 有问题了,开始排查。

果然,passenger 启动失败了,导致无法访问 Rails 应用才报的 403 错误。

启动 passenger 失败的主要原因是因为其无法兼容当前系统版本的 openssl(1.0.x版本),现在摆在我面前的有两条路:

  1. 升级 Passenger
  2. 降级系统的 openssl(这个后续我会另外补充一篇文章分享)

因为 Rails 应用使用的 rails 和 ruby 版本的原因,我只能选择第 2 条路,然后重新编译 ruby(需要将openssl模块编译进去),否则 passenger 也无法启动。

完成之后,再去使用 /bin/passenger-memory-stats 检查一下 passenger 运行状态,结果显示正常,Rails 应用的网站也可以正常访问了。

至此,问题解决。

MySQL笔记

发表于 2022-12-18 | 分类于 Server , DB , Tools |

简介

一直使用着 MySQL,可能是因为现代化的编程框架太牛,差点让我忘记了原始的 SQL 怎么写了,再加上 DBA 的加持让我在 MySQL 上的‘造诣’越发卑微。发现很多自己遇到的问题是曾经已经解决过却被自己忽略的问题。

无论是因为 MySQL 版本问题,还是个人专业度问题,我还是觉得很有必要把这些问题记录下来,为后续解决问题提高效率。

~

写过的关于 MySQL 的文章:

  • MySQL8.0.15在Win10上的折腾记
  • 微服务: MySQL基本操作
  • 微服务: 结合MySQL实现登录注册
  • MySQL主键值被我用完了
  • 导入MySQL数据库文件

这份笔记会持续更新下去。

授权问题

明明给数据库用户进行了授权,但是显示无法本地访问?

当不加 @ 选项时,效果与加 @'%' 是一样的,'%' 从名义上包括任何主机,% 必须加上引号,不然与 @ 放在一起可能不会被辨认出。

不过因为 MySQL 版本问题(我在 MySQL 5.5.x 版本就遇到这样的问题)'%' 不包括 localhost,需要单独对 @'localhost' 进行赋值。

1
2
3
4
5
6
# DB_NAME.*:数据库下的所有表
# 'name'@'localhost':指定用户 name 的 localhost
# 'PASSWORD':指定用户 name 的密码
GRANT ALL PRIVILEGES ON DB_NAME.* TO 'name'@'localhost' IDENTIFIED BY 'PASSWORD' WITH GRANT OPTION;

flush privileges;

MySQL 主从

1、显示主、从运行状态

在 MySQL-Master 上面可以执行

1
show master status\G

在 MySQL-Slave 上面可以执行

1
2
3
4
show master status\G

# 显示的信息更加全面,包括 Master 的情况都有
show slave status\G

Slave 上面,我们主要看下下面两项是否正常:

1
2
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

基本命令

显示当前登录 mysql 的用户

1
select current_user();

查看当前用户拥有的权限

1
show grants;

查看其他 MySQL 用户的权限

1
2
3
4
# 把 name 换成你自己的登录账号名称
show grants for name@localhost;

show grants for name;

Ruby on Rails 实践:更换 aloe 首页

发表于 2022-11-13 | 分类于 Ruby-on-Rails |

简介

在 Ruby on Rails 实践课程:创建 aloe 项目 中我们已经看到了 Rails 跑起来的样子,截至到目前我们还没有写一行代码,只是简单的执行了几个命令,项目就跑起来了。是不是简单地令人发指 😄

在本篇中,朋友们可以了解到:

  • 如何通过 rails g 创建控制器?
  • 如何通过 rails routes 查看控制器的路由?
  • 如何修改工程的路由配置?
  • ERB 文件是什么?

接下来我们给 aloe 换个首页,让它显示 “Hello aloe”。

改头换面

1、创建控制器

同理,我们还是使用 rails 命令创建一个 welcome 控制器

1
rails g controller welcome index 

用 rails g(是 rails generate 的简称)命令创建 welcome 控制器的同时也为其增加了一个 action 即 index,如下所示。

create app/controllers/welcome_controller.rb

route get ‘welcome/index’
invoke erb
create app/views/welcome
create app/views/welcome/index.html.erb
invoke test_unit
create test/controllers/welcome_controller_test.rb
invoke helper
create app/helpers/welcome_helper.rb
invoke test_unit

index 这个 action 也是 rails 里面经常说的路由(route),就类似于你在浏览器访问的地址一样。

可见,执行 rails g 命令后,不仅帮我们创建了控制器也创建了对应的视图文件。

2、路由

在进行接下来的操作之前,我们使用 rails routes 命令看下当前控制器 welcome 有哪些路由了。

Usage:

rails routes [options]

Options:

-c, [–controller=CONTROLLER] # Filter by a specific controller, e.g. PostsController or Admin::PostsController.

-g, [–grep=GREP] # Grep routes by a specific pattern.

-E, [–expanded], [–no-expanded] # Print routes expanded vertically with parts explained.

1
rails routes -c WelcomeController

Prefix Verb URI Pattern Controller#Action

welcome_index GET /welcome/index(.:format) welcome#index

root GET / welcome#index

Verb 指的是 HTTP 方法。

从上面结果可以看出,WelcomeController 有两个路由,对应的 action 都是 welcome#index,其路由名称分别为 welcome_index_path、root_path,在下面的 erb 文件中我们会用到这两个路由名称。

我们修改一下 config/routes.rb 文件,配置一下默认页面地址为 welcome#index

1
2
3
4
5
6
Rails.application.routes.draw do
get 'welcome/index'
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# Defines the root path route ("/")
root "welcome#index"
end

重新启动 aole 服务(rails s),从浏览器打开 http://127.0.0.1:3000/

3、ERB

找到关于 ERB 的解释是在 github-ruby/erb 上面看到的,它是一个简单而强大的 ruby 模版系统( An easy to use but powerful templating system for Ruby),很多人说它是 embedded Ruby 的简称。

我们可以看到 aole 工程中的 view 视图文件是以 .erb 为结尾的, .erb 的模板文件混合使用 ERB(嵌入式 Ruby)和 HTML 编写,扩展名是 .builder 的模板文件使用 Builder::XmlMarkup 库编写。

在 ERB 模板中,可以使用 <% %> 和 <%= %> 标签来包含 Ruby 代码。

  • <% %> 标签用于执行不返回任何内容的 Ruby 代码,例如条件、循环或块语句;

  • <%= %> 标签用于输出 Ruby 代码的执行结果的语句;

1
2
3
4
5
<% 不需要显示出来的(写逻辑脚本(Ruby语法) ) %>
<%= 需要显示出来的(变量值或运算结果) %>
<%- 删除前面的空格 %>
<% 删除后面的空格 -%>
<%- 删除前后的空格 -%>

举个实际的例子

1
2
3
4
5
6
7
8
<% unless logged_in? %>
<li><a href="<%= new_user_path %>">注册</a></li>
<li><a href="<%= new_session_path %>">登录</a></li>
<% else %>
<li><a href="#">欢迎 <%= current_user.username %></a></li>
<!--link_to 在使用 delete 方法时总是被强制去使用 get 方法-->
<li><%= link_to '退出', logout_path, method: :delete %></li>
<% end -%>

我们修改一下 aloe/app/views/welcome/index.html.erb 文件保存,内容如下

1
2
3
4
5
6
7
8
9
10
11
<h1>aole</h1>
<p>Hello aole</p>
<body>
<div>
<ul>
<li><a href="<%= welcome_index_path %>">您好,aole</a></li>
<br>
<li><a href="<%= root_path %>">返回</a></li>
</ul>
</div>
</body>

不需要重启 aole 服务,刷新浏览器如下图所示

经过简单的改造,我们的 aole 首页被改变了。点击“您好,aole”,页面显示的内容相同是但地址栏的地址变了。

路由、视图是 rails 中比较重要的内容,后续我也会专门来写这两块的内容。

参考资料

  • Action View 学习向导

CentOS Install Passenger for ROR

发表于 2022-11-06 | 分类于 Ruby-on-Rails |

简介

本篇文章涉及到的内容都是基于阿里云主机上面操作的,具体系统和软件版本如下:

  • CentOS
    • LSB Version: :core-4.1-amd64:core-4.1-noarch
    • Distributor ID: CentOS
    • Description: CentOS Linux release 7.9.2009 (Core)
    • Release: 7.9.2009
    • Codename: Core
  • Ruby:2.7.4
  • Rails:7.0.4
  • Nginx:1.20.1,云服务已经默认安装了
  • Passenger:Phusion Passenger(R) 6.0.15

本篇文章主要目的:

  • 如何在 CentOS 上安装 Passenger
  • 如何通过 Passenger 运行、访问 ruby on rails 应用

安装 ruby

如果直接使用 yum install -y ruby 安装 ruby,其版本是 2.0.x,而我需要安装 2.7.x 版本。

成功安装 ruby 是接下来一切操作的基础,使用 root 账号登录云主机,按照下面步骤操作即可。如果使用非 root 账号安装,需要在下面命令前加 sudo。

1
2
3
4
5
6
7
8
# 安装源
yum install centos-release-scl-rh

# 安装 ruby-devel
# 这里一定要和 ruby 版本对上,否则后面安装 gems 会报错
yum install rh-ruby27-ruby-devel

yum install ruby

检查 ruby 版本,如果不是 ruby-2.7,可以重新执行如下命令

1
yum install -y rh-ruby27

安装完成后,执行

1
scl enable rh-ruby27

配置开机自动切换到 ruby27,新建并编辑文件

vim /etc/profile.d/rh-ruby27.sh

1
2
source /opt/rh/rh-ruby27/enable
export X_SCLS="`scl enable rh-ruby27 'echo $X_SCLS'`"

安装后的 ruby 在 /opt/rh/rh-ruby27/root/usr/bin/ruby 下。

安装 rails

安装 ruby 稍微麻烦一点,接下来我们安装 rails

1
2
3
gem install rails

gem install bundler

我在安装 rails 遇到了一个问题(报错)

gem install rails
Building native extensions. This could take a while…
ERROR: Error installing rails:
ERROR: Failed to build gem native extension.

current directory: /opt/rh/rh-ruby27/root/usr/local/share/gems/gems/racc-1.6.0/ext/racc/cparse
/opt/rh/rh-ruby27/root/usr/bin/ruby -I /opt/rh/rh-ruby27/root/usr/share/rubygems -r ./siteconf20221029-17728-1uvh5rb.rb extconf.rb
mkmf.rb can’t find header files for ruby at /opt/rh/rh-ruby27/root/usr/share/include/ruby.h

You might have to install separate package for the ruby development
environment, ruby-dev or ruby-devel for example.

extconf failed, exit code 1

Gem files will remain installed in /opt/rh/rh-ruby27/root/usr/local/share/gems/gems/racc-1.6.0 for inspection.
Results logged to /opt/rh/rh-ruby27/root/usr/local/lib64/gems/ruby/racc-1.6.0/gem_make.out

卸载已经安装的 ruby-devel,一般都是其版本和 ruby 版本不一致导致的,重新安装对应版本。

1
2
3
4
5
6
# 安装源
yum install centos-release-scl-rh

# 安装 ruby-devel
# 这里一定要和 ruby 版本对上,否则后面安装 gems 会报错
yum install rh-ruby27-ruby-devel

安装 Passenger

安装 Passenger 比较简单,如果你不是使用 root 账号登录,下面命令需要加上 sudo。

1、enable EPEL

EPEL:Extra Packages for Enterprise Linux

1
2
3
4
yum install -y yum-utils
yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-$(< /etc/redhat-release tr -dc '0-9.'|cut -d \. -f1).noarch.rpm
yum-config-manager --enable epel
yum clean all && sudo yum update -y

2、repair potential system issues

避免在安装 Passenger 时,由于一些系统限制导致安装失败

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Ensure curl and nss/openssl are sufficiently up-to-date to talk to the repo
yum update -y

date
# if the output of date is wrong, please follow these instructions to install ntp
# 这里要注意,检查系统时间是否正确,如果不正确需要先调整好再执行下面步骤

yum install -y ntp
chkconfig ntpd on
ntpdate pool.ntp.org
service ntpd start

yum -y install chrony
systemctl enable chronyd
firewall-cmd --permanent --add-service=ntp
firewall-cmd --reload
systemctl restart chronyd

3、install Passenger packages

1
2
3
4
5
6
7
8
# Install various prerequisites
yum install -y curl

# Add our el9 YUM repository
curl --fail -sSLo /etc/yum.repos.d/passenger.repo https://oss-binaries.phusionpassenger.com/yum/definitions/el-passenger.repo

# Install Passenger dynamic Nginx module
yum install -y nginx-mod-http-passenger || { yum-config-manager --enable cr && yum install -y nginx-mod-http-passenger ; }

4、restart Nginx

重启 nginx

1
systemctl restart nginx

5、check installation

检查是否安装成功

1
sudo /usr/bin/passenger-config validate-install

显示如下信息表示成功

1
2
* Checking whether this Phusion Passenger install is in PATH... ✓
* Checking whether there are no other Phusion Passenger installations... ✓

使用如下命令看下运行状态

1
sudo /usr/sbin/passenger-memory-stats

显示类似如下状态表示正常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Version: 6.0.15

--------- Nginx processes ---------
PID PPID VMSize Private Name
-----------------------------------
5672 1 44.1 MB 0.8 MB nginx: master process nginx
8713 5672 44.3 MB 1.0 MB nginx: worker process
8714 5672 44.3 MB 1.0 MB nginx: worker process

----- Passenger processes -----
PID VMSize Private Name
-------------------------------
8699 355.5 MB 2.2 MB Passenger watchdog
8703 1117.0 MB 4.3 MB Passenger core

至此,Passenger 安装完成。

创建 ROR 应用

通过 rails 创建应用比较简单,在这一步我是用非 root 账号创建的即普通账号(ptyh) 创建的应用。

您可以去了解一下如何在 CentOS 中添加用户(添加用户adduser ptyh、设置密码passwd ptyh)。

创建 articles 应用,如下

1
rails new articles

创建成功后的工程 articles 在目录 /home/ptyh/rails_projs 下。

我们可以启动一下这个工程,确保它本身是正常的。

1
rails s -b 0.0.0.0 -p 8080

我在阿里云上面是开放了 8080 端口的,这样你可以通过 云主机公网IP:8080 访问到,看到如下界面表示成功。

确保您的工程运行和访问没有问题后,停止该服务的运行(ctrl+c)。

我们继续往下看~

配置 Nginx + Passenger

这一步至关重要,关系到是否能通过 passenger 成功运行和访问 ROR 应用。

我们去检查一下 passenger 配置,该配置文件在 /etc/nginx/conf.d/passenger.conf 下,内容如下:

1
2
3
passenger_root /usr/share/ruby/vendor_ruby/phusion_passenger/locations.ini;
passenger_ruby /usr/bin/ruby;
passenger_instance_registry_dir /var/run/passenger-instreg;

可以看出 ruby 路径不对,修改如下

1
2
3
passenger_root /usr/share/ruby/vendor_ruby/phusion_passenger/locations.ini;
passenger_ruby /opt/rh/rh-ruby27/root/usr/bin/ruby;
passenger_instance_registry_dir /var/run/passenger-instreg;

如果不做修改(ruby 版本不一致),后续在通过 passenger 启动的 ror 应用程序会报类似 cannot load such file -- bundler/setup (LoadError) 的错误。

接下来,我们配置一下 nginx,其配置文件在 /etc/nginx/nginx.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#user nginx;
# 修改为 nobody
user nobody;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
worker_connections 1024;
}

http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

access_log /var/log/nginx/access.log main;

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 4096;

include /etc/nginx/mime.types;
default_type application/octet-stream;

# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;

server {
listen 80;
listen [::]:80;
server_name _;
#root /usr/share/nginx/html;

# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;

# 新增1:指定环境和开启 passenger
passenger_app_env development;
passenger_enabled on;

# 新增2:指定 rails 工程的 public 目录
root /home/ptyh/rails_projs/articles/public;

error_page 404 /404.html;
location = /404.html {
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
}

修改的地方在文件中都有注释,修改完成后保存,记得重新 reload 该配置文件

1
nginx -s reload

访问 ROR Web 应用

到这里,基本搞定了,还剩最后一公里,冲。。。

之前说过,修改了 nginx 配置后需要重新 reload,另外我们不需要单独去启动 articles 这个项目。

如果我的云主机公网IP是 12x.x12.13.10x,我们在浏览器上打开 http://12x.x12.13.10x:80,大概率是无法正常显示应用的首页的。

查看 nginx error log 可以发现这样的错误:

Error opening ‘/home/ptyh/rails_projs/articles/Passengerfile.json’ for reading: Permission denied (errno=13);
This error means that the Nginx worker process (PID 7991, running as UID 99) does not have permission to access this file.
Please read this page to learn how to fix this problem:
https://www.phusionpassenger.com/library/admin/nginx/troubleshooting/?a=upon-accessing-the-web-app-nginx-reports-a-permission-denied-error;

我们修改一下工程目录权限,命令如下:

1
2
sudo chmod -R g+x,o+x /home/ptyh/rails_projects/articles
sudo chmod -R g+x,o+x /home/ptyh/rails_projects

再次访问 http://12x.x12.13.10x:80 即可。

关键文件

我在这里给大家罗列一下用到的配置文件及其路径。

nginx 配置文件:/etc/nginx/nginx.conf

nginx 日志文件:/var/log/nginx

ruby 可执行文件: /opt/rh/rh-ruby27/root/usr/bin/ruby

passenger 配置文件: /etc/nginx/conf.d/passenger.conf

通过 nginx -t 可以找到 nginx 配置文件路径,在其配置文件中可以看到日志文件路径。

参考资料

  • centos-ruby-devel
  • intall ruby27
  • Install Passenger
  • Troubleshooting Passenger + Nginx and Ruby
  • Getting Started with Rails 使用 Rails 创建项目

Ruby on Rails 实践:创建 aloe 项目

发表于 2022-09-04 | 分类于 Ruby-on-Rails |

在看正文之前,说一个发生的真实案例。

产品的业务后端是 PHP 写的,而其他一些基础服务是 C++ 开发的。不幸的是产品线上出了一个事故,原因是 PHP 写的一个 API 响应速度过慢,导致整个客户端卡顿,客户端同事抱怨服务端写的 API 垃圾,C++ 同事鄙视 PHP 的同事,C++ 同事现场撸了这个 API 并进行了严格的测试,结论是这个 API 如果用 C++ 写不用 5 毫秒就可以响应任何客户端的请求。一时间项目组陷入了深度怀疑 PHP 的漩涡之中,仿佛罪魁祸首就是那帮写 PHP 的人一样。最后复盘总结发现原来是业务后端架构设计不合理导致的跟编程语言没有半毛钱关系。

编程语言之间确实存在一定的鄙视链,选择哪种编程语言要提前做好规划,综合现有的业务场景、人才储备来考虑,能解决当下问题才是王道。Ruby 不是最好的,但它能解决我遇到的问题,我知道我目前需要它。

简介

本次课程主要跟大家分享一下,如何使用 rails 命令创建工程,同时可以了解到:

  • rails 工程目录以及作用

  • 配置和修改 gem 源

创建项目

使用 rails 创建项目的命令如下

1
rails new APP_PATH [options]

在创建项目之前,检查一下是否已经安装了 sqlite3 这个数据库,没有的话请查阅资料自行安装一下。

检查方法

1
sqlite3 --version

指定 rails 版本创建项目,选项 --skip-bundle 是为了跳过安装 gems,后面会详细说。

1
rails _7.0.3.1_ new ~/work/aloe --skip-bundle

不到 2s 的时间,会在你的 ~/work 目录下有个名为 aloe 的文件夹,它就是我们创建的项目目录。

工程目录介绍

下表列出了对应文件夹包含的内容以及作用,便于大家查阅。

序号 文件/文件夹 作用
1 app/ 包含应用的(MVC)控制器、模型、视图、辅助方法、邮件程序、频道、作业和静态资源文件。这个文件夹跟我们日常开发关系最大
2 bin/ 包含用于启动应用的 rails 脚本,以及用于安装、更新、部署或运行应用的其他脚本
3 config/ 配置应用的路由、数据库等。
4 config.ru 基于 Rack 的服务器所需的 Rack 配置,用于启动应用
5 db/ 包含当前数据库的模式,以及数据库迁移文件
6 Gemfile, Gemfile.lock 这两个文件用于指定 Rails 应用所需的 gem 依赖。Bundler gem 需要用到这两个文件
7 lib/ 应用的扩展模块
8 log/ 应用日志文件
9 public/ 仅有的可以直接从外部访问的文件夹,包含静态文件和编译后的静态资源文件
10 Rakefile 定位并加载可在命令行中执行的任务。这些任务在 Rails 的各个组件中定义。如果要添加自定义任务,请不要修改 Rakefile,直接把自定义任务保存在 lib/tasks 文件夹中即可
11 README.md 应用的自述文件,说明应用的用途、安装方法等
12 storage 磁盘服务的活动存储文件。跟 Active Storage 有关,后面用到再说
13 test/ 单元测试、固件和其他测试装置。详情请参阅Rails 应用测试指南
14 tmp/ 临时文件(如缓存和 PID 文件)
15 vendor/ 包含第三方代码如第三方 gem,在生产环境我们可以直接把 gems 放到这里
16 .gitignore 告诉 Git 要忽略的文件(或模式)
17 .ruby-version 记录工程使用的 ruby 版本

运行项目

更改 gem 源,修改 Gemfile 修改完成后,保存。

1
2
# source "https://rubygems.org"
source "https://gems.ruby-china.com"

运行项目,执行

1
2
3
4
5
# 安装 gems
bundle install

# 运行项目
rails s

在浏览器访问 http://127.0.0.1:3000 就可以看到对应的页面。

这里补充一个小知识点,rails s 是 rails server 命令的简写。关于它的用法还有很多,随着大家的深入学习也会逐渐接触到的。

Usage:

rails server -u [thin/puma/webrick] [options]

Options:

-e, [–environment=ENVIRONMENT] # Specifies the environment to run this server under (test/development/production).

-p, [–port=port] # Runs Rails on the specified port - defaults to 3000.

-b, [–binding=IP] # Binds Rails to the specified IP - defaults to ‘localhost’ in development and ‘0.0.0.0’ in other environments’.

-c, [–config=file] # Uses a custom rackup configuration.

​ # Default: config.ru

-d, [–daemon], [–no-daemon] # Runs server as a Daemon.

-u, [–using=name] # Specifies the Rack server used to run the application (thin/puma/webrick).

-P, [–pid=PID] # Specifies the PID file - defaults to tmp/pids/server.pid.

-C, [–dev-caching], [–no-dev-caching] # Specifies whether to perform caching in development.

​ [–early-hints], [–no-early-hints] # Enables HTTP/2 early hints.

​ [–log-to-stdout], [–no-log-to-stdout] # Whether to log to stdout. Enabled by default in development when not daemonized.

参考资料

  • Getting Started with Rails 使用 Rails 创建项目

Ruby on Rails 实践:课程导读

发表于 2022-09-04 | 分类于 Ruby-on-Rails |

写在前面

第一次听说 Ruby 这门编程语言是在 2012 年,那个时候的 Ruby 是 1.9.x 版本,截至到本文写的时候 Ruby 已经发布了 3.x 版本了。

Ruby 在国内并没有那么火,用 Ruby 进行开发的人也很少,如果不是 Rails 估计 Ruby 早就被人忘得一干二净了。现在在国内找 Ruby on Rails 的学习资料少之又少,无形之中给自己的学习带来了一定的成本。在我了解和初步学习 Ruby on Rails 之后,发现它学习成本不高,并且能够很快的实现你的一些想法,在 Web 开发领域,有它就够了。

编程语言和框架无所谓对错,就看你用它来做什么,有需要就学吧。我想把自己的一些学习实践拿出来跟大家分享一下,希望能够帮助到有需要的人。

学习这套课程需要你有一定的编程基础,至少你需要做好如下几点准备

  1. 有 Java/C#/C/C++/Javascript/Python/PHP/Rust 等其中一种编程语言基础;
  2. 了解或者熟悉 MVC,了解 B/S、C/S 等架构;
  3. 会基本的 Ruby 编程,关于 Ruby 版本的发布历程可以参考 Ruby News 网站拍;
  4. 了解 HTML/CSS 前端编程,会一些基本的 Linux 命令操作;
  5. 了解 Redis/SQLite/Mysql 或者其他数据库基本知识,会使用常用的 SQL 语句。

如果你没有上面的全部基础也没关系,可以边看边学,遇到不懂的知识可以留言评论给我或者自学。请您记住兴趣才是最好的老师,心里只要充满爱,那里都是阳光明媚。我也是利用业余时间来完成这套课程的,内容肯定有不少遗漏和不足的地方,请大家多多指正。

课程目录

目录是动态更新的,希望大家耐心等待⌛️

项目篇

1、创建 aloe 项目

本小节介绍了项目环境的准备以及如何创建项目,本篇教程可以 点击我 直达现场。

  • 安装相关的软件和 Ruby 版本
  • Ruby on Rails 环境搭建

本次课程使用的版本

  • Ruby:3.0.0

  • Rails:7.0.x

2、给 aloe 画个简妆

Ruby on Rails 实践:更换 aloe 首页

在这一个小节中,我介绍了如下内容

  • 如何通过 rails g 创建控制器?
  • 如何通过 rails routes 查看控制器的路由?
  • 如何修改工程的路由配置?
  • ERB 文件是什么?

部署篇

1、CentOS Install Passenger

  • 如何安装 nginx + passenger
  • 如何通过 passenger 访问应用

CentOS7.9 安装 mysql5.7

发表于 2022-04-30 | 分类于 Server , DB , Tools |

简介

在 CentOS 7 上面安装 MySQL5.7 经历了一点小挫折,特此记录,给有需要的朋友做个参考。

我的云主机 CentOS 版本

1
2
3
4
5
6
7
> lsb_release -a

LSB Version: :core-4.1-amd64:core-4.1-noarch
Distributor ID: CentOS
Description: CentOS Linux release 7.9.2009 (Core)
Release: 7.9.2009
Codename: Core

当然你要是不想安装指定版本的 MySQL,直接使用 yum install mysql 也可以。

安装 MySQL

因现有工程等缘故,需要在云主机上面安装 MySQL5.7 版本。

在网上找了挺多安装方法但总是事与愿违,会出现各种各样的问题,还好在 MySQL 官方文档 找到了解决方案。所以说遇到问题还是要到官网去找方案。

如果你已经使用 root 身份登录了主机,在下面的步骤中可以不使用 sudo。

0、检查是否已经安装了 mysql 或者 mariadb

1
rpm -qa | grep mariadb

如果找到了,就先删除

1
rpm -e --nodeps mariadb-libs-x.x.xx-1.el7_5.x86_64

同样的道理查找 mysql,如有也删除即可。

1、Adding the Yum Repository

1
sudo yum localinstall mysql57-community-release-el7-11.noarch.rpm

如果出现类似 Failed to set locale, defaulting to C 这样的错误,说明该源无法找到,可以换中方式:

1
sudo yum localinstall mysql57-community-release-el7.rpm

关于 mysql 的 rpm 源可以在 http://repo.mysql.com/ 找。

2、Selecting a Release Series

执行如下命令前,记得安装 yum -y install yum-utils

1
2
3
4
5
yum repolist all | grep mysql

yum-config-manager --enable mysql57-community

yum repolist enabled | grep mysql

在这一步也可能发现找不到下载的源,可以使用如下方法解决。

1
2
3
4
5
cd /usr/local/src

wget https://repo.mysql.com/mysql57-community-release-el7-9.noarch.rpm

rpm -ivh mysql57-community-release-el7-9.noarch.rpm

3、Install

1
2
3
sudo yum install mysql-community-server
# 上面安装不行的话,就使用下面的命令
sudo yum -y install mysql-server

注意:如果你是 CentOS8,还需要在执行此步骤操作前,需要执行如下命令:

1
sudo yum module disable mysql

在安装过程中,可能会出现下面的错误(此时 MySQL 并没有安装成功)

Public key for mysql-community-libs-compat-5.7.38-1.el7.x86_64.rpm is not installed

Failing package is: mysql-community-libs-compat-5.7.38-1.el7.x86_64

GPG Keys are configured as: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-mysql

需要升级一下 GPG 然后重新安装,方式如下:

1
2
3
rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022

yum install mysql-community-server

4、Start mysqld

1
sudo service mysqld start

下面给出安装 MySQL 成功后,默认的配置文件路径,方便后续使用。

  • 配置文件:/etc/my.cnf
  • 日志文件:/var/log/mysqld.log
  • 启动脚本:/usr/lib/systemd/system/mysqld.service
  • socket文件:/var/run/mysqld/mysqld.pid

使用 MySQL

经过上面简单 4 步就可以轻松的完成 MySQL 的安装,接下来我们开始使用它。

1
mysql -uroot -p

直接回车(Enter),提示如下错误:

1
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

解决上述问题,需要先想办法登入 MySQL,然后再修改 root 用户的密码。

如何解决这个错误而进行登入呢?

MySQL 安装完成之后,生成的默认密码在 /var/log/mysqld.log 日志文件中,我们可以使用 grep 命令在日志中找到临时密码(temporary password)。

1
2
3
grep 'temporary password' /var/log/mysqld.log
# 或者使用下面的命令
grep "password" /var/log/mysqld.log

可以看到临时密码信息:2022-04-30T04:40:47.234502Z 1 [Note] A temporary password is generated for root@localhost: Tq%y:sUnC7;d,用该密码登入 MySQL 即可。

MySQL 5.7 默认安装了密码安全检查插件(validate_password),默认密码检查策略要求密码必须包含大小写字母、数字和特殊符号,并且长度不能少于8位。如果设置的密码不符合规范和要求,进行对应的操作会提示类似密码不符合规范的错误。可以查看 MySQL官网密码详细策略 了解更多这方面的知识。

登入成功之后,修改 root 用户的密码:

1
ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass4!';

后续可以通过如下方式(update)修改 root 用户的密码:

1
2
3
update user set authentication_string=password('MyNewPass4!') where user='root';

flush privileges;

以上操作完成后,需要重启一下 MySQL 服务。

1
service mysqld restart

另外还有一种解决方案,就是修改 my.cnf 配置文件

1
sudo vim /etc/my.cnf

在 [mysqld] 下面新增 skip-grant-tables

1
2
3
4
[mysqld]
...

skip-grant-tables

同理,以上操作完成后需要重启一下 MySQL 服务。新增的这个配置再次登录 MySQL 无需输入 root 密码。

登入后再用上述方法设置 root 用户的密码即可,修改完成后记得去掉 skip-grant-tables 这个配置。

修改默认编码

MySQL 的字符编码,可以通过下述方式查看

1
show variables like 'character%';

我们通过编辑 /etc/my.cnf 配置文件来改变默认编码,分别在对应的标签下面增加如下内容即可。

1
2
3
4
5
6
7
8
[mysqld]
character-set-server=utf8

[client]
default-character-set=utf8

[mysql]
default-character-set=utf8

需要重启一下 MySQL 服务。

1
service mysqld restart

增加用户

默认只允许 root 用户在本地(即本机上)登录,如果其它机器要连接或者访问 mysql,必须添加一个允许远程连接或者访问的帐户。

当然你也可以设置让 root 用户进行远程访问,但这样就很不安全,一般也不会这么做。

1
2
use mysql;
select host,user,authentication_string from user;
host user authentication_string
localhost root *88195A6507F4892C6CED9F6E30BA6C609AF5AFA7
localhost mysql.session *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE

下面新增一个允许远程连接的帐户 lisi,注意设置的密码要符合 MySQL 复杂度要求,否则设置会失败。

1
2
3
GRANT ALL PRIVILEGES ON *.* TO 'lisi'@'%' IDENTIFIED BY 'lisi2018!A' WITH GRANT OPTION;

flush privileges;

再次查看一下用户会发现多了 lisi 这个用户。

host user authentication_string
localhost root *88195A6507F4892C6CED9F6E30BA6C609AF5AFA7
localhost mysql.session *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE
% lisi *86BA32081A204071832FE6D1DECD57D9519D6411

当然也可以授权root进行任何ip的访问。

1
2
3
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root_password' WITH GRANT OPTION;

flush privileges;

重置 root 密码

如果不小心忘记了 MySQL 的 root 用户登录密码,不要紧张,通过下面简单几步的操作就可以重置。

1、修改配置文件

在 /etc/my.cnf (可能你的配置文件在其他目录如 /etc/mysql/my.cnf),文件中新增

1
skip-grant-tables

2、重启服务

1
service mysql restart

3、登录

在命令行直接输入 mysql 即可。

1
mysql

4、重置 root 密码

依次执行如下命令即可。

1
2
3
4
5
6
USE mysql;

# 注意 new_password 是你要重新设置的密码
UPDATE user SET authentication_string = password ('new_password') WHERE User = 'root';
flush privileges;
quit

5、再次修改配置文件

记得注释掉在第1步中增加的内容

1
# skip-grant-tables

6、重启 mysql 服务

7、使用 root 登录

1
mysql -uroot -p

如果你在安装过程中,遇到了文中没有提到的问题,请耐心解决也可以给我留言,一起进步!


祝大家五一节日快乐,生活幸福

12…20>

193 日志
16 分类
163 标签
© 2024 veryitman