Showing posts with label flutter. Show all posts
Showing posts with label flutter. Show all posts

Friday

Microservices Application with Flutter Flask MongoDB RabbitMQ

A complete microservice application setup with a Flutter app, MongoDB, and RabbitMQ, along with all the necessary files and folder structure. The setup uses Docker Compose to orchestrate the services.


Folder Structure

```

microservice-app/

├── backend/

│   ├── Dockerfile

│   ├── requirements.txt

│   ├── main.py

│   └── config.py

├── frontend/

│   ├── Dockerfile

│   ├── pubspec.yaml

│   └── lib/

│       └── main.dart

├── docker-compose.yml

└── README.md

```


1. `docker-compose.yml`

```yaml

version: '3.8'


services:

  backend:

    build: ./backend

    container_name: backend

    ports:

      - "8000:8000"

    depends_on:

      - mongodb

      - rabbitmq

    environment:

      - MONGO_URI=mongodb://mongodb:27017/flutterdb

      - RABBITMQ_URI=amqp://guest:guest@rabbitmq:5672/

    networks:

      - microservice-network


  mongodb:

    image: mongo:latest

    container_name: mongodb

    ports:

      - "27017:27017"

    networks:

      - microservice-network


  rabbitmq:

    image: rabbitmq:3-management

    container_name: rabbitmq

    ports:

      - "5672:5672"

      - "15672:15672"

    networks:

      - microservice-network


  frontend:

    build: ./frontend

    container_name: frontend

    ports:

      - "8080:8080"

    depends_on:

      - backend

    networks:

      - microservice-network


networks:

  microservice-network:

    driver: bridge

```


2. Backend Service


2.1 `backend/Dockerfile`

```dockerfile

FROM python:3.9-slim


WORKDIR /app


COPY requirements.txt requirements.txt

RUN pip install -r requirements.txt


COPY . .


CMD ["python", "main.py"]

```


2.2 `backend/requirements.txt`

```txt

fastapi

pymongo

pika

uvicorn

```


2.3 `backend/config.py`

```python

import os


MONGO_URI = os.getenv('MONGO_URI')

RABBITMQ_URI = os.getenv('RABBITMQ_URI')

```


2.4 `backend/main.py`

```python

from fastapi import FastAPI

from pymongo import MongoClient

import pika

import config


app = FastAPI()


client = MongoClient(config.MONGO_URI)

db = client.flutterdb


# RabbitMQ Connection

params = pika.URLParameters(config.RABBITMQ_URI)

connection = pika.BlockingConnection(params)

channel = connection.channel()


@app.get("/")

async def read_root():

    return {"message": "Backend service running"}


@app.post("/data")

async def create_data(data: dict):

    db.collection.insert_one(data)

    channel.basic_publish(exchange='', routing_key='flutter_queue', body=str(data))

    return {"message": "Data inserted and sent to RabbitMQ"}

```


3. Frontend Service


3.1 `frontend/Dockerfile`

```dockerfile

FROM cirrusci/flutter:stable


WORKDIR /app


COPY . .


RUN flutter build web


CMD ["flutter", "run", "-d", "chrome"]

```


3.2 `frontend/pubspec.yaml`

```yaml

name: flutter_app

description: A new Flutter project.


version: 1.0.0+1


environment:

  sdk: ">=2.7.0 <3.0.0"


dependencies:

  flutter:

    sdk: flutter

  http: ^0.13.3


dev_dependencies:

  flutter_test:

    sdk: flutter

```


#### 3.3 `frontend/lib/main.dart`

```dart

import 'package:flutter/material.dart';

import 'package:http/http.dart' as http;


void main() {

  runApp(MyApp());

}


class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      title: 'Flutter Demo',

      theme: ThemeData(

        primarySwatch: Colors.blue,

      ),

      home: MyHomePage(),

    );

  }

}


class MyHomePage extends StatefulWidget {

  @override

  _MyHomePageState createState() => _MyHomePageState();

}


class _MyHomePageState extends State<MyHomePage> {

  Future<void> sendData() async {

    final response = await http.post(

      Uri.parse('http://backend:8000/data'),

      body: {'key': 'value'},

    );

    print('Response status: ${response.statusCode}');

    print('Response body: ${response.body}');

  }


  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: Text('Flutter Microservice App'),

      ),

      body: Center(

        child: ElevatedButton(

          onPressed: sendData,

          child: Text('Send Data to Backend'),

        ),

      ),

    );

  }

}

```


4. `README.md`

```markdown

# Microservice Application


## Overview


This is a microservice application setup consisting of a Flutter app (frontend), a FastAPI service (backend), MongoDB, and RabbitMQ. All services are orchestrated using Docker Compose.


## How to Run


1. Clone the repository:

   ```bash

   git clone https://github.com/your-repo/microservice-app.git

   cd microservice-app

   ```


2. Build and run the containers:

   ```bash

   docker-compose up --build

   ```


3. Access the services:

   - Frontend: `http://localhost:8080`

   - Backend: `http://localhost:8000`

   - RabbitMQ Management: `http://localhost:15672`

   - MongoDB: `mongodb://localhost:27017`

```


### Instructions to Run the Application

1. Ensure Docker and Docker Compose are installed on your machine.

2. Place the folder structure and files as described above.

3. Navigate to the root of the `microservice-app` folder.

4. Run `docker-compose up --build` to build and start the application.

5. Access the frontend on `http://localhost:8080`, backend on `http://localhost:8000`, and RabbitMQ Management UI on `http://localhost:15672`.


This setup provides a working microservice application with a Flutter frontend, FastAPI backend, MongoDB for storage, and RabbitMQ for messaging.