нам может понадобиться выполнять потоковую передачу для нескольких вещей при работе с крупномасштабными системами, такими как вызов нескольких API, когда это необходимо, и сохранение их в кеше, если это часто используемые данные и т. д.… для таких вещей нам может не понадобиться создавать функции и вызывать их всякий раз это необходимо. Особенно, когда вы хотите обрабатывать данные асинхронно. В этом случае мы можем просто создать поток и читать данные из потока всякий раз, когда это требуется.
Для читателей код будет простым и понятным 👍.
обновлен базовый поток… пожалуйста, просмотрите приведенный ниже код с объяснением и дайте мне знать, если возникнут какие-либо сомнения/предложения/ошибки в моем коде.
package main import ( "fmt" "math/rand" ) func main() { streamingDataUsingChannelAndGoRoutines() } func streamingDataUsingChannelAndGoRoutines() { // send signal to stop channel once you are done with streaming the data (optional)(have to handled by stream owner) stop := make(chan bool) // it will return read only channel for readers publisher := stream(stop) read(publisher) } // it will return read only channel so it will not block the execution / it will not wait to write something into channel/avoids dead lock func stream(stop <-chan bool) <-chan int { // unbuffered channel to stream data // this will useful when you want stream live data when ever required //ch := make(chan int) // buffered channel to stream data // this will be useful when you want to store some data in advance in buffer or cache // ans use whenever it is required directly from buffer ch := make(chan int,2) // this go func will run in background and push data consistently to the channel go func() { // closing the channel once streaming gets stop request defer close(ch) for { select { case <-stop: return case ch <- rand.Int(): // eg use case:- we do an api call and store the data here } } }() return ch } // reader func read(value <-chan int) { // iterating/reading the data for 5 times for i := 1; i <= 5; i++ { // we can read from channel stream any number of times fmt.Println(<-value, <-value, i) } }