Redis Crud로 빠르게 이동 예시
종속성 및 환경 변수 설치
데이터베이스 연결의 값을 사용자의 값으로 바꾸세요.
#env file REDIS_ADDRESS=localhost REDIS_PORT=6379 REDIS_PASSWORD=123456 REDIS_DB=0 #install on go go get github.com/redis/go-redis/v9
관리자 Redis
manage.go에 파일을 생성합니다. 여기에는 다른 모듈 및 서비스 등에서 redis와 연결하는 방법이 포함됩니다.
package main import ( "fmt" "github.com/redis/go-redis/v9" "os" "strconv" ) const CustomerDb = 0 type RedisManager struct { Db int Client *redis.Client } func NewRedisClient(customerDb int) (*RedisManager, error) { address := os.Getenv("REDIS_ADDRESS") if address == "" { return nil, fmt.Errorf("REDIS_ADDRESS is not set") } password := os.Getenv("REDIS_PASSWORD") if password == "" { return nil, fmt.Errorf("REDIS_PASSWORD is not set") } port := os.Getenv("REDIS_PORT") if port == " " { return nil, fmt.Errorf("REDIS_PORT is not set") } db := os.Getenv("REDIS_DB") if db == "" { return nil, fmt.Errorf("REDIS_DB is not set") } redisDb, err := strconv.Atoi(db) if err != nil { return nil, fmt.Errorf("REDIS_DB is not a number") } cli := redis.NewClient(&redis.Options{ Addr: fmt.Sprintf("%s:%s", address, port), Password: password, DB: redisDb, }) return &RedisManager{ Client: cli, Db: customerDb, }, nil } func (rd *RedisManager) SetDb(db int) { rd.Db = db }
엔터티(고객) 저장소 관리를 위한 구조체 생성
redis 연결을 관리하기 위한 구조체를 만들고 redis 엔터티(CRUD 작업 및 쿼리)와 상호 작용하는 모든 메서드를 가져옵니다
이 구조를 사용하면 엔터티(고객) 데이터에 액세스해야 할 때마다 이를 인스턴스화하고 저장소 패턴으로 사용할 수 있습니다.
type CustomerRepo struct { Cli *RedisManager Db int } func NewCustomerRepo() (*CustomerRepo, error) { cli, err := NewRedisClient(CustomerDb) if err != nil { return nil, err } return &CustomerRepo{ Cli: cli, }, nil }
구조체 엔터티 만들기
Customer 엔터티에 bun 필드와 매핑되는 태그를 추가합니다.
redis:"-"는 redis에 저장할 필드와의 관계를 해제합니다. 하나의 파일을 원하거나 구조체를 저장하지 않으려면 태그를 추가하지 마세요.
type Customer struct { ID string `redis:"id"` Name string `redis:"name"` Email string `redis:"email"` Phone string `redis:"phone"` Age int `redis:"age"` }
CRUD 방법
엔티티로부터 정보를 저장, 업데이트 또는 가져오는 방법의 예
이러한 메서드는 CustomersRepo 엔터티에서 사용됩니다.
그들은 정보와 함께 고객 엔터티를 받았고 작업에 따라 결과를 반환했습니다.
새 기록을 저장하세요
func (c *CustomerRepo) Save(customer *Customer) error { return c.Cli.Client.HSet(context.TODO(), customer.ID, customer).Err() }
ID에 대한 기록 가져오기
func (c *CustomerRepo) Get(id string) (*Customer, error) { customer := &Customer{} resMap := c.Cli.Client.HGetAll(context.TODO(), id) if resMap.Err() != nil { return nil, resMap.Err() } if len(resMap.Val()) == 0 { return nil, nil } err := resMap.Scan(customer) if err != nil { return nil, err } return customer, nil }
새 기록 업데이트
func (c *CustomerRepo) Update(customer *Customer) error { return c.Cli.Client.HSet(context.TODO(), customer.ID, customer).Err() }
새 기록 삭제
func (c *CustomerRepo) Delete(id string) error { return c.Cli.Client.Del(context.TODO(), id).Err() }
코드 예제 검토
테스트용 Redis 예시
위 내용은 Redis Crud로 빠르게 이동 예시의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Golang은 성능과 확장 성 측면에서 Python보다 낫습니다. 1) Golang의 컴파일 유형 특성과 효율적인 동시성 모델은 높은 동시성 시나리오에서 잘 수행합니다. 2) 해석 된 언어로서 파이썬은 천천히 실행되지만 Cython과 같은 도구를 통해 성능을 최적화 할 수 있습니다.

Golang은 동시성에서 C보다 낫고 C는 원시 속도에서 Golang보다 낫습니다. 1) Golang은 Goroutine 및 Channel을 통해 효율적인 동시성을 달성하며, 이는 많은 동시 작업을 처리하는 데 적합합니다. 2) C 컴파일러 최적화 및 표준 라이브러리를 통해 하드웨어에 가까운 고성능을 제공하며 극도의 최적화가 필요한 애플리케이션에 적합합니다.

goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity, 효율성, 및 콘크리 론 피처

Golang은 빠른 개발 및 동시 시나리오에 적합하며 C는 극도의 성능 및 저수준 제어가 필요한 시나리오에 적합합니다. 1) Golang은 쓰레기 수집 및 동시성 메커니즘을 통해 성능을 향상시키고, 고전성 웹 서비스 개발에 적합합니다. 2) C는 수동 메모리 관리 및 컴파일러 최적화를 통해 궁극적 인 성능을 달성하며 임베디드 시스템 개발에 적합합니다.

goimpactsdevelopmentpositively throughlyspeed, 효율성 및 단순성.

Golang과 Python은 각각 고유 한 장점이 있습니다. Golang은 고성능 및 동시 프로그래밍에 적합하지만 Python은 데이터 과학 및 웹 개발에 적합합니다. Golang은 동시성 모델과 효율적인 성능으로 유명하며 Python은 간결한 구문 및 풍부한 라이브러리 생태계로 유명합니다.

Golang과 C의 성능 차이는 주로 메모리 관리, 컴파일 최적화 및 런타임 효율에 반영됩니다. 1) Golang의 쓰레기 수집 메커니즘은 편리하지만 성능에 영향을 줄 수 있습니다. 2) C의 수동 메모리 관리 및 컴파일러 최적화는 재귀 컴퓨팅에서 더 효율적입니다.

Golang과 C는 각각 공연 경쟁에서 고유 한 장점을 가지고 있습니다. 1) Golang은 높은 동시성과 빠른 발전에 적합하며 2) C는 더 높은 성능과 세밀한 제어를 제공합니다. 선택은 프로젝트 요구 사항 및 팀 기술 스택을 기반으로해야합니다.
