This is part 4 of Developing Instagram Clone series, other parts are linked below

  1. Developing Instagram Clone: Introduction.
  2. Developing Instagram Clone: Discovery Service.
  3. Developing Instagram Clone: Auth Service
  4. Developing Instagram Clone: Media Service.
  5. Developing Instagram Clone: Post Service.
  6. Developing Instagram Clone: Graph Service.
  7. Developing Instagram Clone: Newsfeed Service.
  8. Developing Instagram Clone: Gateway Service.
  9. Developing Instagram Clone: Front-end Service

In real, the responsibilities of the media service should be to upload an image to a cloud object storage like Amazon S3 and stores a metadata about the image in a data store, MongoDB in our case.

To avoid paying for object storage services, media service has an additional responsibility (hack) to store the images on file system and to serve the images.

As always we start by cloning the Media service from GitHub.

Spring static resource configurations

The first step we need is to configure spring to serve static content in order to generate a URL to access each uploaded image.

Let’s look into StaticResourceConfiguration.

@Configuration
public class StaticResourceConfiguration implements WebMvcConfigurer {

    @Value("${file.upload-dir}")
    private String uploadDirectory;

    @Value("${file.path.prefix}")
    private String filePathPrefix;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler(filePathPrefix + "/**")
                .addResourceLocations("file:" + uploadDirectory);
    }
}

Here we configure spring to map the following URL

http://{host}:{port}/{filePathPrefix}/{image_filename}

to

{uploadDirectory}/{image_filename}

Let’s have a look into application.yml file to give a concrete example.

spring:
  ...
  
file:
  upload-dir: /home/amr/insta-clone-images/
  path:
    prefix: /images

server:
  port: 8000

Line 5, sets the upload directory, don’t forget to change this to an existing directory on your machine.

The prefix is set to “/images” and service port to 8080.

Let’s assume we that the image file name is “image1.jpg” , the above would translates to

http://localhost:8080/images/image1.jpg

This will be mapped to the following filesystem path

/home/amr/insta-clone-images/image1.jpg

#microservices #cloud #mongodb #aws #developer

Microservices In Practice: Developing Instagram Clone — Media Service
6.80 GEEK