【K8S/redis】Django应用连接无密码redis--20220913

应用版本:

20220909-gaga_meeting_0.9(uswgi+redis无密码+celery+beat)-0.9.10-勿动!
seasonzhang/gaga_meeting:0.9.10

redis相关settings.py

"""
Django settings for GAGA project.

Generated by 'django-admin startproject' using Django 3.2.7.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path
import os
from django.utils.translation import gettext_lazy as _


# 环境变量(含默认值)
#REDIS_LOCATION = os.environ.get('REDIS_LOCATION',"redis://localhost:6379/1")  # 务必使用redis://redis:6379/1,否则会报错
#REDIS_LOCATION = os.environ.get('REDIS_LOCATION',"redis://redis:6379/1")  # 务必使用redis://redis:6379/1,否则会报错
REDIS_LOCATION = os.environ.get('REDIS_LOCATION',"redis://106.52.14.84:6379/1") 
DJANGO_DEBUG = os.environ.get('DJANGO_DEBUG', True)



# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
LOG_DIR = Path(__file__).resolve().parent.parent / 'log'

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-+=99f6x#@pq9f5=riae=8skj)6vu55vptpo9-in#yl*+2qfop@'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
DEBUG = DJANGO_DEBUG

ALLOWED_HOSTS = ['*']





# Application definition

INSTALLED_APPS = [
    'simpleui',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'GAGA_meeting',
    'django_celery_beat',
]


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',### 多语言中间件
    'django.middleware.cache.UpdateCacheMiddleware',#redis中间件
    'django.middleware.common.CommonMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',#redis中间件
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'GAGA.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'GAGA.wsgi.application'



# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        #'NAME': BASE_DIR / 'db.sqlite3',
        'NAME': Path(__file__).resolve().parent /'SQL' /'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# 修改中文,Django内部设置zh_Hans方法指向中文 
LANGUAGES = [
    ('zh-hans', _('Chinese')),
    ('en', _('English')),
]

LANGUAGE_CODE = 'zh-hans' 
# LANGUAGE_CODE = 'en-us'

LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

# 修改中国时区
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = False
# USE_TZ = True
USE_I18N = True
USE_L10N = True



# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
# 通过url直接访问我在项目中的静态文件
STATIC_URL = '/static/'
# 部署静态文件时(pyhtonmanage.pycollectstatic)所有的静态文静聚合的目录
STATIC_ROOT = os.path.join(BASE_DIR, "/static/")
# STATICFILES_DIRS告诉django,首先到STATICFILES_DIRS里面寻找静态文件,其次再到各个app的static文件夹里面找
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')



# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'



LOGIN_URL = '/user_login/'

DATE_FORMAT = 'Y-m-d'





LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    # 'formatters': {
    #     'simple': { # exact format is not important, this is the minimum information
    #         'format': '%(asctime)s %(name)-12s %(lineno)d %(levelname)-8s %(message)s',
    #     },
    # },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },

        'mail_admins': { # Add Handler for mail_admins for `warning` and above
            # 'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
        },
        'file': {
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOG_DIR, 'admin.log'),
        },

    },

    'root': {
        'handlers': ['console', 'file','mail_admins'],
        'level': 'INFO',
    },
}



# K8S redis
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": REDIS_LOCATION,
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "PASSWORD":"redis654321",
            "SOCKET_CONNECT_TIMEOUT": 5,  # in seconds
            "SOCKET_TIMEOUT": 5,  # r/w timeout in seconds
        }
    }
}




CELERY_BROKER_URL = REDIS_LOCATION
CELERY_RESULT_BACKEND = REDIS_LOCATION
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Shanghai'
CELERYD_MAX_TASKS_PER_CHILD = 10
CELERYD_LOG_FILE = os.path.join(BASE_DIR, "logs", "celery_work.log")
CELERYBEAT_LOG_FILE = os.path.join(BASE_DIR, "logs", "celery_beat.log")


# CELERY_BEAT忽略时区错误
DJANGO_CELERY_BEAT_TZ_AWARE = False

相关yaml档案及启动顺序

1.先启动redis,并将redis IP:port暴露给应用
redis-deployment,svc-无密码.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    kompose.cmd: kompose convert
    kompose.version: 1.24.0 (7c629530)
  creationTimestamp: null
  labels:
    io.kompose.service: redis
  name: redis
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: redis
  strategy: {}
  template:
    metadata:
      annotations:
        kompose.cmd: kompose convert
        kompose.version: 1.24.0 (7c629530)
      creationTimestamp: null
      labels:
        io.kompose.service: redis
    spec:
      containers:
        - image: redis:alpine
          name: gaga-meeting-redis
          ports:
            - containerPort: 6379
          resources:
            requests:
              cpu: 100m
              memory: 100Mi
            limits:
              cpu: 200m
              memory: 200Mi
      restartPolicy: Always
status: {}

---

apiVersion: v1
kind: Service
metadata:
  annotations:
    kompose.cmd: kompose convert
    kompose.version: 1.24.0 (7c629530)
  creationTimestamp: null
  labels:
    io.kompose.service: redis
  name: redis
spec:
  type: LoadBalancer
  ports:
    - name: "6379"
      port: 6379
      targetPort: 6379
  selector:
    io.kompose.service: redis
status:
  loadBalancer: {}

2.先启动应用
web-deployment,svc.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    kompose.cmd: kompose convert
    kompose.version: 1.24.0 (7c629530)
  creationTimestamp: null
  labels:
    io.kompose.service: web
  name: web
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: web
  strategy:
    type: Recreate
  template:
    metadata:
      annotations:
        kompose.cmd: kompose convert
        kompose.version: 1.24.0 (7c629530)
      creationTimestamp: null
      labels:
        io.kompose.service: web
    spec:
      containers:
        - command:
            - /bin/sh
            - /code/package/start.sh
          image: seasonzhang/gaga_meeting:0.9.10
          imagePullPolicy: IfNotPresent
          name: gaga-meeting-web
          ports:
            - containerPort: 8000
          resources:
            requests:
              cpu: 500m
              memory: 500Mi
            limits:
              cpu: 500m
              memory: 500Mi
---
apiVersion: v1
kind: Service
metadata:
  annotations:
    kompose.cmd: kompose convert
    kompose.version: 1.24.0 (7c629530)
  creationTimestamp: null
  labels:
    io.kompose.service: web
  name: web
spec:
  type: LoadBalancer
  ports:
    - name: "8000"
      port: 8000
      targetPort: 8000
      rotocol: TCP
  selector:
    io.kompose.service: web
  externalIPs: #集群内互访
    - 10.0.8.10
    - 10.43.207.93
status:
  loadBalancer: {}

3.启动celery和beat
celery-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    kompose.cmd: kompose convert
    kompose.version: 1.24.0 (7c629530)
  creationTimestamp: null
  labels:
    io.kompose.service: celery
  name: celery
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: celery
  strategy:
    type: Recreate
  template:
    metadata:
      annotations:
        kompose.cmd: kompose convert
        kompose.version: 1.24.0 (7c629530)
      creationTimestamp: null
      labels:
        io.kompose.service: celery
    spec:
      containers:
        - command:
            - /bin/sh
            - /code/package/start-celery.sh
          image: seasonzhang/gaga_meeting:0.9.10
          name: gaga-meeting-celery
          resources:
            requests:
              cpu: 100m
              memory: 100Mi
            limits:
              cpu: 200m
              memory: 200Mi
      #     volumeMounts:
      #       - mountPath: /code/package/GAGA/SQL
      #         name: C
      # restartPolicy: Always
      # volumes:
      #   - name: C
      #     persistentVolumeClaim:
      #       claimName: C
status: {}

beat-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    kompose.cmd: kompose convert
    kompose.version: 1.24.0 (7c629530)
  creationTimestamp: null
  labels:
    io.kompose.service: beat
  name: beat
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: beat
  strategy:
    type: Recreate
  template:
    metadata:
      annotations:
        kompose.cmd: kompose convert
        kompose.version: 1.24.0 (7c629530)
      creationTimestamp: null
      labels:
        io.kompose.service: beat
    spec:
      containers:
        - command:
            - /bin/sh
            - /code/package/start-beat.sh
          image: seasonzhang/gaga_meeting:0.9.10
          name: gaga-meeting-beat
          resources:
            requests:
              cpu: 100m
              memory: 100Mi
            limits:
              cpu: 200m
              memory: 200Mi
#           volumeMounts:
#             - mountPath: /code/package/GAGA/SQL
#               name: C
#       restartPolicy: Always
#       volumes:
#         - name: C
#           persistentVolumeClaim:
#             claimName: C
# status: {}

启动成功在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值