» Python:使用Kafka构建事件驱动微服务 » 4. 消费者:推荐服务 » 4.4 推荐服务集成

推荐服务集成

让我们在书店 web 服务中调用推荐服务以显示用户兴趣推荐。

添加配置项,service/web/infrastructure/config/config.py:

@@ -28,6 +28,7 @@ class ApplicationConfig:
 @dataclass
 class RemoteServiceConfig:
     trend_url: str
+    rec_url: str
 
 
 @dataclass

填入配置值,service/web/config.yml:

@@ -13,4 +13,5 @@ mq:
     - localhost:9094
   topic: "lr-book-searches"
 remote:
   trend_url: "http://localhost:8001/trends"
+  rec_url: "http://localhost:8002/recommendations?uid="

调整 service/web/application/executor/book_operator.py:

@@ -6,7 +6,7 @@ import urllib.request
 
 
 from .. import dto
-from ....domain.model import Book, Trend
+from ....domain.model import Book, Trend, Interest
 from ...domain.gateway import BookManager
 from ...infrastructure.mq import MQHelper
 
@@ -38,6 +38,10 @@ class BookOperator():
             data = response.read()
             return json.loads(data.decode('utf-8'))
 
+    def get_interests(self, interests_url: str) -> List[Interest]:
+        with urllib.request.urlopen(interests_url) as response:
+            return json.loads(response.read().decode('utf-8'))
+
 
 def _convert(b: Book) -> Dict:
     d = asdict(b)

集成推荐服务结果,service/web/adapter/router.py:

@@ -67,12 +67,19 @@ def make_router(app: FastAPI, templates_dir: str, remote: RemoteServiceConfig, w
         except Exception as e:
             rest_handler._logger.warn(f"Failed to get trends: {e}")
             trends = []
+        try:
+            interests = rest_handler.book_operator.get_interests(
+                rest_handler.remote.rec_url + user_id)
+        except Exception as e:
+            rest_handler._logger.warn(f"Failed to get interests: {e}")
+            interests = []
         resp = templates.TemplateResponse(
             name="index.html", context={
                 "request": request,
                 "title": "LiteRank Book Store",
                 "books": books,
                 "trends": trends,
+                "recommendations": interests,
                 "q": q,
             }
         )

渲染 recommendationsservice/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 class="grid grid-cols-4 gap-2 font-mono">
+            {% for r  in recommendations %}
+                <div class="bg-white p-4 rounded-md border-gray-300 shadow mt-2">
+                    <div class="text-lg font-bold">{{r.title}}</div>
+                    <span class="font-serif italic text-sm">{{r.author}}</span>
                 </div>
+            {% endfor %}
             </div>
         </div>
     </div>

确保热搜服务和推荐服务都在运行,然后重启 web 服务,你将在首页看到如下结果。

Recommendations

两个服务都已经集成!赞🎉!