指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

symfony框架使用redis:

  • 安装拓展
composer require snc/redis-bundle
  • client选择
这里使用predis: composer require predis/predis
默认使用的是phpredis(需要 ext-redis 拓展,直接 use Redis;即可)
  • 修改配置 config/packages/snc_redis.yaml
snc_redis:
    clients:

# Define your clients here. The example below connects to database 0 of the default Redis server.
#
# See https://github.com/snc/SncRedisBundle/blob/master/docs/README.md for instructions on
# how to configure the bundle.
#
        default:
            type: predis
            alias: default
            dsn: "%env(REDIS_URL)%"
  • 使用
    首先在services.yaml里添加配置
services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/'
            - '../src/Kernel.php'

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones

	#使用predis的client,service为 snc_redis.default
    Predis\ClientInterface: '@snc_redis.default' 
  • 控制器中使用:
<?php

namespace App\Controller\Admin;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Predis\ClientInterface;//使用上面配置的predis client,会自动注入

class IndexController extends AbstractController
{
    #[Route('/admin', name: 'admin')]
    public function index(Request $request, ClientInterface $client): Response
    {
        //通过redis 命令进行操作
        $client->select(1);
        $client->set('name','wuhan');

        dd($client->get('name'));
        return $this->renderForm('admin/index.html.twig');
    }
}