- 
                Notifications
    You must be signed in to change notification settings 
- Fork 5
feat: add reconnect for mq producer #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            Echin-h
  wants to merge
  1
  commit into
  main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
reconnect
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from all commits
      Commits
    
    
  File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
|  | @@ -3,15 +3,23 @@ package mq | |
| import ( | ||
| "context" | ||
| "crypto/md5" | ||
| "errors" | ||
| "fmt" | ||
| "math" | ||
| "time" | ||
|  | ||
| amqp "github.com/rabbitmq/amqp091-go" | ||
| "go.opentelemetry.io/otel" | ||
| "golang.org/x/sync/singleflight" | ||
| ) | ||
|  | ||
| type Producer struct { | ||
| Conn *amqp.Connection | ||
| Channel *amqp.Channel | ||
|  | ||
| amqpURI string // AMQP URI for RabbitMQ reconnection | ||
| sf *singleflight.Group | ||
|  | ||
| appId string | ||
| } | ||
|  | ||
|  | @@ -21,7 +29,9 @@ func NewProducer(appId string, amqpURI string) (*Producer, error) { | |
| } | ||
|  | ||
| p := &Producer{ | ||
| appId: appId, | ||
| appId: appId, | ||
| amqpURI: amqpURI, | ||
| sf: new(singleflight.Group), | ||
| } | ||
|  | ||
| var err error | ||
|  | @@ -34,6 +44,53 @@ func NewProducer(appId string, amqpURI string) (*Producer, error) { | |
| return p, nil | ||
| } | ||
|  | ||
| func (p *Producer) isConnected() bool { | ||
| return !p.Conn.IsClosed() && !p.Channel.IsClosed() | ||
| } | ||
|  | ||
| func (p *Producer) connectFn() error { | ||
| if p.isConnected() { | ||
| return nil | ||
| } | ||
|  | ||
| _, err, _ := p.sf.Do("reconnect", func() (interface{}, error) { | ||
| var lastErr error | ||
| for i := 0; i < 3; i++ { | ||
| if p.isConnected() { | ||
| return nil, nil | ||
| } | ||
|  | ||
| if i > 0 { | ||
| time.Sleep(time.Second * time.Duration(math.Pow(2, float64(i-1)))) | ||
| } | ||
|  | ||
| conn, channel, err := initConnection(p.amqpURI) | ||
| if err != nil { | ||
| lastErr = fmt.Errorf("reconnect attempt %d failed: %s", i+1, err) | ||
| continue | ||
| } | ||
|  | ||
| oldConn := p.Conn | ||
| oldChannel := p.Channel | ||
| p.Conn = conn | ||
| p.Channel = channel | ||
|  | ||
| if oldChannel != nil { | ||
| _ = oldChannel.Close() | ||
| } | ||
| if oldConn != nil { | ||
| _ = oldConn.Close() | ||
| } | ||
|  | ||
| return nil, nil | ||
| } | ||
|  | ||
| return nil, lastErr | ||
| }) | ||
|  | ||
| return err | ||
| } | ||
|  | ||
| func (p *Producer) PublishNotice(ctx context.Context, data *NoticeTemplate, options ...string) error { | ||
|  | ||
| if data == nil { | ||
|  | @@ -107,6 +164,28 @@ func (p *Producer) publish(ctx context.Context, key string, msg []byte, opts map | |
| Headers: headers, | ||
| }) | ||
|  | ||
| if err != nil && errors.Is(err, amqp.ErrClosed) { | ||
| if err = p.connectFn(); err != nil { | ||
| return err | ||
| } | ||
|  | ||
| err = p.Channel.PublishWithContext( | ||
| ctx, | ||
| exchangeName, | ||
| key, | ||
| false, | ||
| false, | ||
| amqp.Publishing{ | ||
| ContentType: "application/json", | ||
| DeliveryMode: amqp.Persistent, | ||
| Body: msg, | ||
| AppId: p.appId, | ||
| UserId: opts[UserIdKey], | ||
| MessageId: fmt.Sprintf("%x", md5.Sum(msg)), | ||
| Headers: headers, | ||
| }) | ||
| } | ||
| 
      Comment on lines
    
      +167
     to 
      +187
    
   There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion 重构建议:消除代码重复并改进重试逻辑 当前实现存在代码重复问题,且重试逻辑可以更加健壮。 建议将发布逻辑提取到一个内部方法中,并实现更完善的重试机制: -	err := p.Channel.PublishWithContext(
-		ctx,
-		exchangeName,
-		key,
-		false,
-		false,
-		amqp.Publishing{
-			ContentType:  "application/json",
-			DeliveryMode: amqp.Persistent,
-			Body:         msg,
-			AppId:        p.appId,
-			UserId:       opts[UserIdKey],
-			MessageId:    fmt.Sprintf("%x", md5.Sum(msg)),
-			Headers:      headers,
-		})
-
-	if err != nil && errors.Is(err, amqp.ErrClosed) {
-		if err = p.connectFn(); err != nil {
-			return err
-		}
-
-		err = p.Channel.PublishWithContext(
-			ctx,
-			exchangeName,
-			key,
-			false,
-			false,
-			amqp.Publishing{
-				ContentType:  "application/json",
-				DeliveryMode: amqp.Persistent,
-				Body:         msg,
-				AppId:        p.appId,
-				UserId:       opts[UserIdKey],
-				MessageId:    fmt.Sprintf("%x", md5.Sum(msg)),
-				Headers:      headers,
-			})
-	}
-
-	return err
+	publishing := amqp.Publishing{
+		ContentType:  "application/json",
+		DeliveryMode: amqp.Persistent,
+		Body:         msg,
+		AppId:        p.appId,
+		UserId:       opts[UserIdKey],
+		MessageId:    fmt.Sprintf("%x", md5.Sum(msg)),
+		Headers:      headers,
+	}
+
+	// 最多重试 2 次
+	for i := 0; i < 2; i++ {
+		err := p.Channel.PublishWithContext(
+			ctx,
+			exchangeName,
+			key,
+			false,
+			false,
+			publishing,
+		)
+		
+		if err == nil {
+			return nil
+		}
+		
+		if !errors.Is(err, amqp.ErrClosed) {
+			return err
+		}
+		
+		// 尝试重连
+		if reconnectErr := p.connectFn(); reconnectErr != nil {
+			return fmt.Errorf("publish failed: %v, reconnect failed: %v", err, reconnectErr)
+		}
+	}
+	
+	return fmt.Errorf("publish failed after %d attempts", 2)这样可以: 
 
 🤖 Prompt for AI Agents | ||
|  | ||
| return err | ||
|  | ||
| } | ||
|  | ||
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
存在线程安全问题,需要加锁保护连接替换操作
当前的连接替换逻辑(第73-83行)存在竞态条件。在读取旧连接和关闭它们之间,其他 goroutine 可能正在使用这些连接,导致潜在的并发问题。
建议使用互斥锁保护连接替换操作:
type Producer struct { Conn *amqp.Connection Channel *amqp.Channel + mu sync.RWMutex // 保护连接的读写 amqpURI string sf *singleflight.Group appId string }然后在
connectFn中:同时,需要在
isConnected()和publish()方法中使用读锁来访问连接。另外,建议将错误格式化从
%s改为%v以更好地处理各种错误类型:🤖 Prompt for AI Agents