laravel5.7 使用 redis

laravel 使用 redis

1、使用composer 安装 predis

  • 切换镜像源 (这里使用华为镜像源:https://mirrors.huaweicloud.com/)
image.png
composer config -g repo.packagist composer https://mirrors.huaweicloud.com/repository/php/
  • 开始安装predis
composer require predis/predis

2、项目根目录下的config/database.php配置好redis

'redis' => [

        'client' => 'predis',//predis

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_DB', 0),
        ],
    ],

如果redis作为缓存工具,可以设置如下

'redis' => [

        'client' => 'predis',

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_DB', 0),
        ],

        'cache' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_CACHE_DB', 1),
        ],

    ],

3、在.env文件中添加redis 对应的虚拟机号

image.png

注:再此之前,虚拟机必须安装好redis,这里使用unbuntu18 安装

sudo apt-get install redis-server
  • 想进行远程访问redis ,必须修改redis 配置文件
vim /etc/redis/redis.conf 
# By default, if no "bind" configuration directive is specified, Redis listens
# for connections from all the network interfaces available on the server.
# It is possible to listen to just one or multiple selected interfaces using
# the "bind" configuration directive, followed by one or more IP addresses.
#
# Examples:
#
# bind 192.168.1.100 10.0.0.1
# bind 127.0.0.1 ::1
#
# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the
# internet, binding to all the interfaces is dangerous and will expose the
# instance to everybody on the internet. So by default we uncomment the
# following bind directive, that will force Redis to listen only into
# the IPv4 lookback interface address (this means Redis will be able to
# accept connections only from clients running into the same computer it
# is running).
#
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT THE FOLLOWING LINE.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bind 0.0.0.0   #修改此处为 bind 0.0.0.0

  • 重启redis服务 并 查看状态
service redis-server restart
service redis-server status

参考链接(Ubuntu下Redis的安装配置):https://blog.csdn.net/yf_man/article/details/78144029

4、在项目文件中引入redis

use Illuminate\Support\Facades\Redis;

public function test(){
    Redis::set('a',1);//设置
    Redis::get('a');//获取
}

你可能感兴趣的:(laravel5.7 使用 redis)