Home Database Redis How to correctly set the configuration parameters of mongodb and redis development environment and production environment

How to correctly set the configuration parameters of mongodb and redis development environment and production environment

Jun 03, 2023 pm 08:04 PM
redis mongodb

When we write code, we usually develop it on our own computer first, and then deploy the code to the server. If a piece of code involves reading and writing a database, or accessing some other online service interfaces, then during development, in order not to affect the online environment, we usually separate the database in the test environment and the database in the online environment.

For example, our program needs to access MongoDB and Redis, so in the code, we may write like this:

import pymongo
import redis

handler = pymongo.MongoClient('mongodb://username:password@127.0.0.1:27017').db.col
client = redis.Redis(host='127.0.0.1', port=6379, password='xxxx')
Copy after login

When you want to deploy the program to the online environment, you manually change the MongoDB connection parameters and Redis connection parameters in the code to the parameters of the online environment. Then submit the code to Git, pull the latest code on the server and deploy it.

However, when you want to modify a new function and test it again, you need to modify these connection parameters to the parameters of the test environment and operate on your own computer. If you forget to modify and run directly, dirty data may be written to the online environment.

So, someone may use environment variables to control the parameters read, for example:

import os
import redis
import pymongo

if os.getenv('env', 'prod'):  # 线上环境 
    MONGODB_URI = 'mongodb://username:password@xx.xx.xx.xx:27017'
    REDIS_PARAMS = {'host': 'xx.xx.xx.xx', 'port': 6379, 'password': 'xxxx'}
else:  # 测试环境
    MONGODB_URI = 'mongodb://username:password@127.0.0.1:27017'
    REDIS_PARAMS = {'host': '127.0.0.1', 'port': 6379, 'password': 'xxxx'}

handler = pymongo.MongoClient(MONGODB_URI).db.col
client = redis.Redis(**REDIS_PARAMS)
Copy after login

In this way, you don’t need to manually modify the connection parameters of the database. Just set the environment variable env of the online environment to prod, and then the program will be deployed to the online environment. It automatically uses the parameters of the online database. As long as the environment variable env is not prod elsewhere, such as on your computer, or the environment variable simply does not exist, the parameters of the development environment will be automatically used.

Doing this does avoid problems caused by forgetting to modify parameters, but there is another problem: if other people also have access to this Git source, then they will know how to connect to the database in the online environment. They even manipulate data in the online environment without authorization, causing security risks or privacy leaks.

In order to be more secure, you can use a special file to store the configuration parameters, and the program reads the parameters from the file. The online environment file contains online parameters, and the development environment file contains development parameters. This configuration file is not uploaded to Git.

For example, we create a config.json file whose content is:

{
    "MONGODB_URI": "mongodb://username:password@127.0.0.1:27017",
    "REDIS_PARAMS": {"host": "127.0.0.1", "port": 6379, "password": "xxxx"}
}
Copy after login

Then our code is modified like this:

import os
import json
import redis
import pymongo

CONFIG_PATH = '/etc/config/config.json'
if not os.path.exists(CONFIG_PATH):
    print('配置文件不存在,自动使用测试环境参数!')
    MONGODB_URI = 'mongodb://username:password@127.0.0.1:27017'
    REDIS_PARAMS = {'host': '127.0.0.1', 'port': 6379, 'password': 'xxxx'}
else:
    with open(CONFIG_PATH, encoding='utf-8') as f:
        config = json.load(f)
        MONGODB_URI = config['MONGODB_URI']
        REDIS_PARAMS = config["REDIS_PARAMS"]
    
handler = pymongo.MongoClient(MONGODB_URI).db.col
client = redis.Redis(**REDIS_PARAMS)
Copy after login

The above is the detailed content of How to correctly set the configuration parameters of mongodb and redis development environment and production environment. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

PostgreSQL performance optimization under Debian PostgreSQL performance optimization under Debian Apr 12, 2025 pm 08:18 PM

To improve the performance of PostgreSQL database in Debian systems, it is necessary to comprehensively consider hardware, configuration, indexing, query and other aspects. The following strategies can effectively optimize database performance: 1. Hardware resource optimization memory expansion: Adequate memory is crucial to cache data and indexes. High-speed storage: Using SSD SSD drives can significantly improve I/O performance. Multi-core processor: Make full use of multi-core processors to implement parallel query processing. 2. Database parameter tuning shared_buffers: According to the system memory size setting, it is recommended to set it to 25%-40% of system memory. work_mem: Controls the memory of sorting and hashing operations, usually set to 64MB to 256M

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

How to configure slow query log in centos redis How to configure slow query log in centos redis Apr 14, 2025 pm 04:54 PM

Enable Redis slow query logs on CentOS system to improve performance diagnostic efficiency. The following steps will guide you through the configuration: Step 1: Locate and edit the Redis configuration file First, find the Redis configuration file, usually located in /etc/redis/redis.conf. Open the configuration file with the following command: sudovi/etc/redis/redis.conf Step 2: Adjust the slow query log parameters in the configuration file, find and modify the following parameters: #slow query threshold (ms)slowlog-log-slower-than10000#Maximum number of entries for slow query log slowlog-max-len

How to install redis in centos7 How to install redis in centos7 Apr 14, 2025 pm 08:21 PM

How to encrypt data in Debian MongoDB How to encrypt data in Debian MongoDB Apr 12, 2025 pm 08:03 PM

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

See all articles