github.com/songzhibin97/gkit@v1.2.13/distributed/example/send/send.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"time"
     7  
     8  	"github.com/songzhibin97/gkit/generator"
     9  
    10  	"github.com/songzhibin97/gkit/distributed/example"
    11  	"github.com/songzhibin97/gkit/distributed/task"
    12  )
    13  
    14  var generate = generator.NewSnowflake(time.Now(), 1)
    15  
    16  func generateIDWithSignature(signature *task.Signature) *task.Signature {
    17  	id, _ := generate.NextID()
    18  	signature.ID = strconv.FormatUint(id, 10)
    19  	return signature
    20  }
    21  
    22  func generateID() string {
    23  	id, _ := generate.NextID()
    24  	return strconv.FormatUint(id, 10)
    25  }
    26  
    27  func main() {
    28  	server := example.InitServer()
    29  	if server == nil {
    30  		panic("server is empty")
    31  	}
    32  	var (
    33  		addTask0, addTask1, addTask2                      task.Signature
    34  		multiplyTask0, multiplyTask1                      task.Signature
    35  		sumIntsTask, sumFloatsTask, concatTask, splitTask task.Signature
    36  		panicTask                                         task.Signature
    37  		longRunningTask                                   task.Signature
    38  	)
    39  	initTasks := func() {
    40  		addTask0 = task.Signature{
    41  			Name:   "add",
    42  			Router: server.GetConfig().ConsumeQueue,
    43  			Args: []task.Arg{
    44  				{
    45  					Type:  "int64",
    46  					Value: int64(1),
    47  				},
    48  				{
    49  					Type:  "int64",
    50  					Value: int64(1),
    51  				},
    52  			},
    53  		}
    54  
    55  		addTask1 = task.Signature{
    56  			Name:   "add",
    57  			Router: server.GetConfig().ConsumeQueue,
    58  			Args: []task.Arg{
    59  				{
    60  					Type:  "int64",
    61  					Value: int64(2),
    62  				},
    63  				{
    64  					Type:  "int64",
    65  					Value: int64(2),
    66  				},
    67  			},
    68  		}
    69  
    70  		addTask2 = task.Signature{
    71  			Name:   "add",
    72  			Router: server.GetConfig().ConsumeQueue,
    73  			Args: []task.Arg{
    74  				{
    75  					Type:  "int64",
    76  					Value: int64(5),
    77  				},
    78  				{
    79  					Type:  "int64",
    80  					Value: int64(6),
    81  				},
    82  			},
    83  		}
    84  
    85  		multiplyTask0 = task.Signature{
    86  			Name:   "multiply",
    87  			Router: server.GetConfig().ConsumeQueue,
    88  			Args: []task.Arg{
    89  				{
    90  					Type:  "int64",
    91  					Value: int64(4),
    92  				},
    93  			},
    94  		}
    95  
    96  		multiplyTask1 = task.Signature{
    97  			Name:   "multiply",
    98  			Router: server.GetConfig().ConsumeQueue,
    99  		}
   100  
   101  		sumIntsTask = task.Signature{
   102  			Name:   "sum_ints",
   103  			Router: server.GetConfig().ConsumeQueue,
   104  			Args: []task.Arg{
   105  				{
   106  					Type:  "[]int64",
   107  					Value: []int64{1, 2},
   108  				},
   109  			},
   110  		}
   111  
   112  		sumFloatsTask = task.Signature{
   113  			Name:   "sum_floats",
   114  			Router: server.GetConfig().ConsumeQueue,
   115  			Args: []task.Arg{
   116  				{
   117  					Type:  "[]float64",
   118  					Value: []float64{1.5, 2.7},
   119  				},
   120  			},
   121  		}
   122  
   123  		concatTask = task.Signature{
   124  			Name:   "concat",
   125  			Router: server.GetConfig().ConsumeQueue,
   126  			Args: []task.Arg{
   127  				{
   128  					Type:  "[]string",
   129  					Value: []string{"foo", "bar"},
   130  				},
   131  			},
   132  		}
   133  
   134  		splitTask = task.Signature{
   135  			Name:   "split",
   136  			Router: server.GetConfig().ConsumeQueue,
   137  			Args: []task.Arg{
   138  				{
   139  					Type:  "string",
   140  					Value: "foo",
   141  				},
   142  			},
   143  		}
   144  
   145  		panicTask = task.Signature{
   146  			Name:   "panic_task",
   147  			Router: server.GetConfig().ConsumeQueue,
   148  		}
   149  
   150  		longRunningTask = task.Signature{
   151  			Name:   "long_running_task",
   152  			Router: server.GetConfig().ConsumeQueue,
   153  		}
   154  	}
   155  	// 发送单个任务
   156  	initTasks()
   157  
   158  	asyncResult, err := server.SendTask(generateIDWithSignature(&addTask0))
   159  	if err != nil {
   160  		fmt.Println("Could not send task: ", err.Error())
   161  		return
   162  	}
   163  	results, err := asyncResult.Get(time.Millisecond * 5)
   164  	if err != nil {
   165  		fmt.Println("Getting task result failed with error: ", err.Error())
   166  		return
   167  	}
   168  	fmt.Println("1 + 1 =", task.HumanReadableResults(results))
   169  
   170  	// 发送入参出参为slice的任务
   171  	asyncResult, err = server.SendTask(generateIDWithSignature(&sumIntsTask))
   172  	if err != nil {
   173  		fmt.Println("Could not send task: ", err.Error())
   174  		return
   175  	}
   176  	results, err = asyncResult.Get(time.Millisecond * 5)
   177  	if err != nil {
   178  		fmt.Println("Getting task result failed with error: ", err.Error())
   179  		return
   180  	}
   181  	fmt.Println("sum([1, 2]) =", task.HumanReadableResults(results))
   182  
   183  	asyncResult, err = server.SendTask(generateIDWithSignature(&sumFloatsTask))
   184  	if err != nil {
   185  		fmt.Println("Could not send task: ", err.Error())
   186  		return
   187  	}
   188  	results, err = asyncResult.Get(time.Millisecond * 5)
   189  	if err != nil {
   190  		fmt.Println("Getting task result failed with error: ", err.Error())
   191  		return
   192  	}
   193  	fmt.Println("sum([1.5, 2.7]) =", task.HumanReadableResults(results))
   194  
   195  	asyncResult, err = server.SendTask(generateIDWithSignature(&concatTask))
   196  	if err != nil {
   197  		fmt.Println("Could not send task: ", err.Error())
   198  		return
   199  	}
   200  	results, err = asyncResult.Get(time.Millisecond * 5)
   201  	if err != nil {
   202  		fmt.Println("Getting task result failed with error: ", err.Error())
   203  		return
   204  	}
   205  	fmt.Println("concat([\"foo\", \"bar\"]) =", task.HumanReadableResults(results))
   206  
   207  	asyncResult, err = server.SendTask(generateIDWithSignature(&splitTask))
   208  	if err != nil {
   209  		fmt.Println("Could not send task: ", err.Error())
   210  		return
   211  	}
   212  	results, err = asyncResult.Get(time.Millisecond * 5)
   213  	if err != nil {
   214  		fmt.Println("Getting task result failed with error: ", err.Error())
   215  		return
   216  	}
   217  	fmt.Println("split([\"foo\"]) =", task.HumanReadableResults(results))
   218  
   219  	// 发送任务组
   220  	initTasks()
   221  	fmt.Println("Group of tasks (parallel execution):")
   222  	group, err := task.NewGroup(generateID(), "group", generateIDWithSignature(&addTask0), generateIDWithSignature(&addTask1), generateIDWithSignature(&addTask2))
   223  	if err != nil {
   224  		fmt.Println("Error creating group:", err.Error())
   225  		return
   226  	}
   227  	asyncResults, err := server.SendGroup(group, 10)
   228  	if err != nil {
   229  		fmt.Println("Could not send group:", err.Error())
   230  	}
   231  	for _, result := range asyncResults {
   232  		results, err := result.Get(time.Millisecond * 5)
   233  		if err != nil {
   234  			fmt.Println("Getting task result failed with error:", err.Error())
   235  			return
   236  		}
   237  		fmt.Println(result.Signature.Args[0].Value,
   238  			result.Signature.Args[1].Value,
   239  			task.HumanReadableResults(results))
   240  	}
   241  
   242  	// 发送具有回调的任务组
   243  	group, err = task.NewGroup(generateID(), "group_with_callback", generateIDWithSignature(&addTask0), generateIDWithSignature(&addTask1), generateIDWithSignature(&addTask2))
   244  	if err != nil {
   245  		fmt.Println("Error creating group:", err.Error())
   246  		return
   247  	}
   248  	callback, err := task.NewGroupCallback(group, "group_callback", generateIDWithSignature(&multiplyTask1))
   249  	if err != nil {
   250  		fmt.Println("Error creating group callback:", err)
   251  		return
   252  	}
   253  	groupCallbackAsyncResult, err := server.SendGroupCallback(callback, 10)
   254  	if err != nil {
   255  		fmt.Println("Could not send group callback:", err.Error())
   256  		return
   257  	}
   258  	results, err = groupCallbackAsyncResult.Get(time.Millisecond * 5)
   259  	if err != nil {
   260  		fmt.Println("Could not send group callback:", err.Error())
   261  		return
   262  	}
   263  	fmt.Println("(1 + 1) * (2 + 2) * (5 + 6) = ", task.HumanReadableResults(results))
   264  
   265  	// 链式任务
   266  	initTasks()
   267  	fmt.Println("Chain of tasks:")
   268  
   269  	chain, err := task.NewChain("chain", generateIDWithSignature(&addTask0), generateIDWithSignature(&addTask1), generateIDWithSignature(&addTask2), generateIDWithSignature(&multiplyTask0))
   270  	if err != nil {
   271  		fmt.Println("Error creating chain:", err)
   272  		return
   273  	}
   274  	chainAsyncResult, err := server.SendChain(chain)
   275  	if err != nil {
   276  		fmt.Println("Could not send chain:", err.Error())
   277  		return
   278  	}
   279  	results, err = chainAsyncResult.Get(time.Millisecond * 5)
   280  	if err != nil {
   281  		fmt.Println("Getting chain result failed with error:", err.Error())
   282  		return
   283  	}
   284  	fmt.Println("(((1 + 1) + (2 + 2)) + (5 + 6)) * 4 = ", task.HumanReadableResults(results))
   285  
   286  	// panic 任务
   287  	asyncResult, err = server.SendTask(generateIDWithSignature(&panicTask))
   288  	if err != nil {
   289  		fmt.Println("Could not send task: ", err.Error())
   290  		return
   291  	}
   292  	_, err = asyncResult.Get(time.Millisecond * 5)
   293  	if err == nil {
   294  		fmt.Println("Error should not be nil if task panicked")
   295  		return
   296  	}
   297  	fmt.Println("Task panicked and returned error = ", err.Error())
   298  
   299  	// 长任务
   300  	asyncResult, err = server.SendTask(generateIDWithSignature(&longRunningTask))
   301  	if err != nil {
   302  		fmt.Println("Could not send task: ", err.Error())
   303  		return
   304  	}
   305  	results, err = asyncResult.Get(time.Millisecond * 5)
   306  	if err != nil {
   307  		fmt.Println("Getting long running task result failed with error: ", err.Error())
   308  		return
   309  	}
   310  	fmt.Println("Long running task returned =", task.HumanReadableResults(results))
   311  }