推荐服务集成
让我们在书店 web 服务中调用推荐服务以显示用户兴趣推荐。
移动 service/recommendation/domain/model/interest.go 到 domain/model/interest.go。
更新以下文件中的 import 路径:
- service/recommendation/application/consumer/interest.go
- service/recommendation/application/executor/interest_operator.go
- service/recommendation/domain/gateway/interest_manager.go
- service/recommendation/infrastructure/database/mongo.go
添加配置项,service/web/infrastructure/config/config.go:
@@ -32,4 +32,5 @@ type MQConfig struct {
// RemoteServiceConfig is the configuration of remote services.
type RemoteServiceConfig struct {
TrendURL string `json:"trend_url" yaml:"trend_url"`
+ RecURL string `json:"rec_url" yaml:"rec_url"`
}
填入配置值,service/web/config.yml:
@@ -10,3 +10,4 @@ mq:
topic: "lr-book-searches"
remote:
trend_url: "http://localhost:8081/trends"
+ rec_url: "http://localhost:8082/recommendations?uid="
调整 service/web/application/executor/book_operator.go:
@@ -61,3 +61,12 @@ func (o *BookOperator) GetTrends(ctx context.Context, trendURL string) ([]*model
}
return trends, nil
}
+
+// GetInterests gets a list of user interests from the remote service
+func (o *BookOperator) GetInterests(ctx context.Context, interestURL string) ([]*model.Interest, error) {
+ var interests []*model.Interest
+ if err := remote.HttpFetch(ctx, interestURL, &interests); err != nil {
+ return nil, err
+ }
+ return interests, nil
+}
集成推荐服务结果,service/web/adapter/router.go:
@@ -75,12 +75,18 @@ func (r *RestHandler) indexPage(c *gin.Context) {
log.Printf("Failed to get trends: %v", err)
trends = make([]*model.Trend, 0)
}
+ interests, err := r.bookOperator.GetInterests(c, r.remoteConfig.RecURL+userID)
+ if err != nil {
+ log.Printf("Failed to get interests: %v", err)
+ interests = make([]*model.Interest, 0)
+ }
// Render the HTML template named "index.html"
c.HTML(http.StatusOK, "index.html", gin.H{
- "title": "LiteRank Book Store",
- "books": books,
- "trends": trends,
- "q": q,
+ "title": "LiteRank Book Store",
+ "books": books,
+ "trends": trends,
+ "recommendations": interests,
+ "q": q,
})
}
渲染 recommendations
,service/web/adapter/templates/index.html:
@@ -57,17 +57,13 @@
<!-- Recommended for You Section -->
<div>
<h2 class="text-2xl font-bold mb-4">Recommended for You</h2>
- <div class="grid grid-cols-2 gap-4 font-mono">
- <!-- Recommended items can be dynamically generated here -->
- <div class="bg-white p-2 rounded-md border-gray-300 shadow">
- Recommended Book 1
- </div>
- <div class="bg-white p-2 rounded-md border-gray-300 shadow">
- Recommended Book 2
- </div>
- <div class="bg-white p-2 rounded-md border-gray-300 shadow">
- Recommended Book 3
- </div>
+ <div class="grid grid-cols-4 gap-2 font-mono">
+ {{range .recommendations}}
+ <div class="bg-white p-4 rounded-md border-gray-300 shadow mt-2">
+ <div class="text-lg font-bold">{{.Title}}</div>
+ <span class="font-serif italic text-sm">{{.Author}}</span>
+ </div>
+ {{end}}
</div>
</div>
</div>
确保热搜服务和推荐服务都在运行,然后重启 web 服务,你将在首页看到如下结果。
两个服务都已经集成!赞🎉!