v1 Publish with retry settings (DEPRECATED)

(DEPRECATED) Publish with retry settings

Code sample

Go

Before trying this sample, follow the Go setup instructions in the Pub/Sub quickstart using client libraries . For more information, see the Pub/Sub Go API reference documentation .

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

  import 
  
 ( 
  
 "context" 
  
 "fmt" 
  
 "io" 
  
 "time" 
  
 "cloud.google.com/go/pubsub" 
  
 vkit 
  
 "cloud.google.com/go/pubsub/apiv1" 
  
 gax 
  
 "github.com/googleapis/gax-go/v2" 
  
 "google.golang.org/grpc/codes" 
 ) 
 func 
  
 publishWithRetrySettings 
 ( 
 w 
  
 io 
 . 
 Writer 
 , 
  
 projectID 
 , 
  
 topicID 
 , 
  
 msg 
  
 string 
 ) 
  
 error 
  
 { 
  
 // projectID := "my-project-id" 
  
 // topicID := "my-topic" 
  
 // msg := "Hello World" 
  
 ctx 
  
 := 
  
 context 
 . 
 Background 
 () 
  
 config 
  
 := 
  
& pubsub 
 . 
  ClientConfig 
 
 { 
  
 PublisherCallOptions 
 : 
  
& vkit 
 . 
 PublisherCallOptions 
 { 
  
 Publish 
 : 
  
 [] 
 gax 
 . 
 CallOption 
 { 
  
 gax 
 . 
 WithRetry 
 ( 
 func 
 () 
  
 gax 
 . 
 Retryer 
  
 { 
  
 return 
  
 gax 
 . 
 OnCodes 
 ([] 
 codes 
 . 
 Code 
 { 
  
 codes 
 . 
 Aborted 
 , 
  
 codes 
 . 
 Canceled 
 , 
  
 codes 
 . 
 Internal 
 , 
  
 codes 
 . 
 ResourceExhausted 
 , 
  
 codes 
 . 
 Unknown 
 , 
  
 codes 
 . 
 Unavailable 
 , 
  
 codes 
 . 
 DeadlineExceeded 
 , 
  
 }, 
  
 gax 
 . 
 Backoff 
 { 
  
 Initial 
 : 
  
 250 
  
 * 
  
 time 
 . 
 Millisecond 
 , 
  
 // default 100 milliseconds 
  
 Max 
 : 
  
 60 
  
 * 
  
 time 
 . 
 Second 
 , 
  
 // default 60 seconds 
  
 Multiplier 
 : 
  
 1.45 
 , 
  
 // default 1.3 
  
 }) 
  
 }), 
  
 }, 
  
 }, 
  
 } 
  
 client 
 , 
  
 err 
  
 := 
  
 pubsub 
 . 
  NewClientWithConfig 
 
 ( 
 ctx 
 , 
  
 projectID 
 , 
  
 config 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "pubsub: NewClient: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 defer 
  
 client 
 . 
 Close 
 () 
  
 t 
  
 := 
  
 client 
 . 
 Topic 
 ( 
 topicID 
 ) 
  
 result 
  
 := 
  
 t 
 . 
 Publish 
 ( 
 ctx 
 , 
  
& pubsub 
 . 
 Message 
 { 
  
 Data 
 : 
  
 [] 
 byte 
 ( 
 msg 
 ), 
  
 }) 
  
 // Block until the result is returned and a server-generated 
  
 // ID is returned for the published message. 
  
 id 
 , 
  
 err 
  
 := 
  
 result 
 . 
 Get 
 ( 
 ctx 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "pubsub: result.Get: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 fmt 
 . 
 Fprintf 
 ( 
 w 
 , 
  
 "Published a message; msg ID: %v\n" 
 , 
  
 id 
 ) 
  
 return 
  
 nil 
 } 
 

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser .

Create a Mobile Website
View Site in Mobile | Classic
Share by: