目前分類:spring boot (3)

瀏覽方式: 標題列表 簡短摘要

 

RabbitMQ is a popular open source message queuing system developed in the erlang language.  RabbitMQ is a standard implementation of AMQP (Advanced Message Queuing Protocol).

Add maven dependency

  1. dependency  >

  2.       groupId  >  org.springframework.boot  </  groupId  >

  3.       artifactId  >  spring-boot-starter-amqp  </  artifactId  >

  4. </  dependency  >

Simple implementation

Configuration

Add the following configuration in application.properties

  1. Spring.rabbitmq.addresses=127.0.0.1:5672

  2. Spring.rabbitmq.username=guest

  3. Spring.rabbitmq.password=guest

  4. Spring.rabbitmq.publisher-confirms=true

  5. Spring.rabbitmq.virtual-host=/

Rabbitmq port description: 5672-amqp, 25672-clustering, 61613-stomp, 1883-mqtt

News producer

  1. Package   com.rabbitmq.send;

  2.  

  3. Import   org.springframework.amqp.rabbit.core.RabbitTemplate;

  4. Import   org.springframework.beans.factory.annotation.Autowired;

  5. Import   org.springframework.stereotype.Component;

  6.  

  7. @Component

  8. Public   class   Sender {

  9.  

  10.     @Autowired

  11.     Private   RabbitTemplate rabbitTemplate;

  12.  

  13.     Public   void   send(String msg) {

  14.         This  .rabbitTemplate.convertAndSend(  "foo"  , msg);

  15.     }

  16. }

Message listener

  1. Package   com.rabbitmq.listener;

  2.  

  3. Import   org.slf4j.Logger;

  4. Import   org.slf4j.LoggerFactory;

  5. Import   org.springframework.amqp.core.Queue;

  6. Import   org.springframework.amqp.rabbit.annotation.RabbitHandler;

  7. Import   org.springframework.amqp.rabbit.annotation.RabbitListener;

  8. Import   org.springframework.context.annotation.Bean;

  9. Import   org.springframework.context.annotation.Configuration;

  10. Import   org.springframework.messaging.handler.annotation.Payload;

  11.  

  12. @Configuration

  13. @RabbitListener  (queues =   "foo"  )

  14. Public   class   Listener {

  15.  

  16.     Private   static   final   Logger LOGGER = LoggerFactory.getLogger(Listener.  class  );

  17.  

  18.     @Bean

  19.     Public   Queue fooQueue() {

  20.         Return   new   Queue(  "foo"  );

  21.     }

  22.  

  23.     @RabbitHandler

  24.     Public   void   process(  @Payload   String foo) {

  25.         LOGGER.info(  "Listener: "   + foo);

  26.     }

  27. }

Test Controller

  1. Package   com.rabbitmq.controller;

  2.  

  3. Import   com.rabbitmq.send.Sender;

  4. Import   org.springframework.beans.factory.annotation.Autowired;

  5. Import   org.springframework.web.bind.annotation.GetMapping;

  6. Import   org.springframework.web.bind.annotation.RestController;

  7.  

  8. Import   javax.servlet.http.HttpServletRequest;

  9.  

  10. @RestController

  11. Public   class   RabbitmqController {

  12.  

  13.     @Autowired

  14.     Private   Sender sender;

  15.  

  16.     @GetMapping  (  "/send"  )

  17.     Public   String send(HttpServletRequest request, String msg) {

  18.         Sender.send(msg);

  19.         Return   "Send OK."  ;

  20.     }

  21. }

Test

Start the service, enter http://127.0.0.1:8080/send?msg=this%20is%20a%20test in the browser, click Enter to see the output in the console

  1. INFO 5559 - [cTaskExecutor-1] c.rabbitmq.listener.Listener : Listener: this is a test

  2. [SimpleAsyncTaskExecutor-1] INFO c.rabbitmq.listener.Listener – Listener: this is a test

Use with ConfirmCallback

Added callback processing, which no longer uses the default configuration of application.properties and will display the configuration information in the use file in the program.

Configuration

  1. Package   com.rabbitmq.config;

  2.  

  3. Import   org.springframework.amqp.rabbit.connection.CachingConnectionFactory;

  4. Import   org.springframework.amqp.rabbit.connection.ConnectionFactory;

  5. Import   org.springframework.amqp.rabbit.core.RabbitTemplate;

  6. Import   org.springframework.beans.factory.annotation.Value;

  7. Import   org.springframework.beans.factory.config.ConfigurableBeanFactory;

  8. Import   org.springframework.context.annotation.Bean;

  9. Import   org.springframework.context.annotation.Configuration;

  10. Import   org.springframework.context.annotation.Scope;

  11.  

  12. @Configuration

  13. Public   class   AmqpConfig {

  14.  

  15.     Public   static   final   String FOO_EXCHANGE =   "callback.exchange.foo"  ;

  16.     Public   static   final   String FOO_ROUTINGKEY =   "callback.routingkey.foo"  ;

  17.     Public   static   final   String FOO_QUEUE =   "callback.queue.foo"  ;

  18.  

  19.     @Value  (  "${spring.rabbitmq.addresses}"  )

  20.     Private   String addresses;

  21.     @Value  (  "${spring.rabbitmq.username}"  )

  22.     Private   String username;

  23.     @Value  (  "${spring.rabbitmq.password}"  )

  24.     Private   String password;

  25.     @Value  (  "${spring.rabbitmq.virtual-host}"  )

  26.     Private   String virtualHost;

  27.     @Value  (  "${spring.rabbitmq.publisher-confirms}"  )

  28.     Private   boolean   publisherConfirms;

  29.  

  30.     @Bean

  31.     Public   ConnectionFactory connectionFactory() {

  32.         CachingConnectionFactory connectionFactory =   new   CachingConnectionFactory();

  33.         connectionFactory.setAddresses(addresses);

  34.         connectionFactory.setUsername(username);

  35.         connectionFactory.setPassword(password);

  36.         connectionFactory.setVirtualHost(virtualHost);

  37.         /** If you want to make a message callback, this must be set to true */

  38.         connectionFactory.setPublisherConfirms(publisherConfirms);

  39.         Return   connectionFactory;

  40.     }

  41.  

  42.     @Bean

  43.     /** Because you want to set the callback class, it should be the prototype type. If it is the singleton type, the callback class is set to the last time. */

  44.     @Scope  (ConfigurableBeanFactory.SCOPE_PROTOTYPE)

  45.     Public   RabbitTemplate rabbitTemplate() {

  46.         RabbitTemplate template =   new   RabbitTemplate(connectionFactory());

  47.         Return   template;

  48.     }

  49.  

  50. }

News producer

  1. Package   com.rabbitmq.send;

  2.  

  3. Import   com.rabbitmq.config.AmqpConfig;

  4. Import   org.slf4j.Logger;

  5. Import   org.slf4j.LoggerFactory;

  6. Import   org.springframework.amqp.rabbit.core.RabbitTemplate;

  7. Import   org.springframework.amqp.rabbit.support.CorrelationData;

  8. Import   org.springframework.beans.factory.annotation.Autowired;

  9. Import   org.springframework.stereotype.Component;

  10.  

  11. Import   java.util.UUID;

  12.  

  13. @Component

  14. Public   class   Sender   implements   RabbitTemplate.ConfirmCallback {

  15.  

  16.     Private   static   final   Logger LOGGER = LoggerFactory.getLogger(Sender.  class  );

  17.  

  18.     Private   RabbitTemplate rabbitTemplate;

  19.  

  20.     @Autowired

  21.     Public   Sender(RabbitTemplate rabbitTemplate) {

  22.         This  .rabbitTemplate = rabbitTemplate;

  23.         This  .rabbitTemplate.setConfirmCallback(  this  );

  24.     }

  25.  

  26.     Public   void   send(String msg) {

  27.         CorrelationData correlationData =   new   CorrelationData(UUID.randomUUID().toString());

  28.         LOGGER.info(  "send: "   + correlationData.getId());

  29.         This  .rabbitTemplate.convertAndSend(AmqpConfig.FOO_EXCHANGE, AmqpConfig.FOO_ROUTINGKEY, msg, correlationData);

  30.     }

  31.  

  32.     /** Callback method */

  33.     @Override

  34.     Public   void   confirm(CorrelationData correlationData,   boolean   ack, String cause) {

  35.         LOGGER.info(  "confirm: "   + correlationData.getId());

  36.     }

  37. }

Message listener

  1. Package   com.rabbitmq.listener;

  2.  

  3. Import   com.rabbitmq.config.AmqpConfig;

  4. Import   org.slf4j.Logger;

  5. Import   org.slf4j.LoggerFactory;

  6. Import   org.springframework.amqp.core.Binding;

  7. Import   org.springframework.amqp.core.BindingBuilder;

  8. Import   org.springframework.amqp.core.DirectExchange;

  9. Import   org.springframework.amqp.core.Queue;

  10. Import   org.springframework.amqp.rabbit.annotation.RabbitHandler;

  11. Import   org.springframework.amqp.rabbit.annotation.RabbitListener;

  12. Import   org.springframework.context.annotation.Bean;

  13. Import   org.springframework.context.annotation.Configuration;

  14. Import   org.springframework.messaging.handler.annotation.Payload;

  15.  

  16. @Configuration

  17. @RabbitListener  (queues = AmqpConfig.FOO_QUEUE)

  18. Public   class   Listener {

  19.  

  20.     Private   static   final   Logger LOGGER = LoggerFactory.getLogger(Listener.  class  );

  21.  

  22.     /** Set switch type */

  23.     @Bean

  24.     Public   DirectExchange defaultExchange() {

  25.         /**

  26.          * DirectExchange: Distribution to the specified queue according to the routingkey

  27.          * TopicExchange: Multiple Keyword Matching

  28.          * FanoutExchange: Distribution of messages to all binding queues, no concept of routingkey

  29.          * HeadersExchange : Matching by adding attribute key-value

  30.          */

  31.         Return   new   DirectExchange(AmqpConfig.FOO_EXCHANGE);

  32.     }

  33.  

  34.     @Bean

  35.     Public   Queue fooQueue() {

  36.         Return   new   Queue(AmqpConfig.FOO_QUEUE);

  37.     }

  38.  

  39.     @Bean

  40.     Public   Binding binding() {

  41.         /** Bind the queue to the switch */

  42.         Return   BindingBuilder.bind(fooQueue()).to(defaultExchange()).with(AmqpConfig.FOO_ROUTINGKEY);

  43.     }

  44.  

  45.     @RabbitHandler

  46.     Public   void   process(  @Payload   String foo) {

  47.         LOGGER.info(  "Listener: "   + foo);

  48.     }

  49. }

Or use the following code instead of the process method of the @RabbitHandler annotation

  1. @Bean

  2. Public   SimpleMessageListenerContainer messageContainer() {

  3.     SimpleMessageListenerContainer container =   new   SimpleMessageListenerContainer(connectionFactory());

  4.     container.setQueues(fooQueue());

  5.     container.setExposeListenerChannel(  true  );

  6.     container.setMaxConcurrentConsumers(  1  );

  7.     container.setConcurrentConsumers(  1  );

  8.     container.setAcknowledgeMode(AcknowledgeMode.MANUAL);   //Set confirm mode manual confirmation

  9.     container.setMessageListener(  new   ChannelAwareMessageListener() {

  10.  

  11.         @Override

  12.         Public   void   onMessage(Message message, Channel channel)   throws   Exception {

  13.             Byte  [] body = message.getBody();

  14.             LOGGER.info(  "Listener onMessage : "   +   new   String(body));

  15.             channel.basicAck(message.getMessageProperties().getDeliveryTag(),   false  );   //Confirm that the message was successfully consumed

  16.         }

  17.     });

  18.     Return   container;

  19. }

 

USEFUL RESOURCES:

 

Spring boot rabbitmq example

 

Spring boot official

 

 

 

文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣()

The traditional way to run a Spring web application on a remote server is to package it into a war file and deploy that file into a servlet container.

Although this method has served us well in the past, managing multiple servlet containers has always been a bit cumbersome.

Spring Boot provides one solution to this problem. It allows us to package our web application into an executable jar file that uses an embedded servlet container.

 requirements:

  • Our Spring Boot application must use Thymeleaf as a templating engine.
  • Our Spring Boot application must provide us a way to monitor it.
  • Our Gradle project must have separate source and resource directories for unit and integration tests.

Creating a Java Project

Because we want to create a Java project, we have to apply the java plgin. We can do this by following these steps:

  1. Apply the Gradle Java plugin.
  2. Set the version of our Java source to 1.8.
  3. Configure Gradle to generate classes for Java 1.8.

Our build.gradle file looks as follows:

1
2
3
4
apply plugin: 'java'
 
sourceCompatibility = 1.8
targetCompatibility = 1.8

 

Adding Integration Tests Into Our Gradle Build

We can add integration tests into our Gradle build by using the Gradle TestSets plugin. Because I have already written a blog post that describes how we can use this plugin, I won’t describe the configuration of this plugin in this blog post.

After we have fulfilled the requirements specified in this blog post, our build.gradle file looks as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath(
                'org.unbroken-dome.gradle-plugins:gradle-testsets-plugin:1.0.2'
        )
    }
}
 
apply plugin: 'java'
apply plugin: 'org.unbroken-dome.test-sets'
 
sourceCompatibility = 1.8
targetCompatibility = 1.8
 
testSets {
    integrationTest { dirName = 'integration-test' }
}
 
project.integrationTest {
    outputs.upToDateWhen { false }
}
 
check.dependsOn integrationTest
integrationTest.mustRunAfter test
 
tasks.withType(Test) {
    reports.html.destination = file("${reporting.baseDir}/${name}")
}

 

Adding Spring Boot Support Into Our Gradle Project

We can add Spring Boot support into our Gradle project by using the Spring Boot Gradle plugin. We can use this plugin by following these steps:

  1. Add the Spring Boot Gradle plugin (version 1.2.5.RELEASE) to the classpath of the build script.
  2. Apply the Spring Boot Gradle plugin.

The source code of our build.gradle file looks as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath(
                'org.springframework.boot:spring-boot-gradle-plugin:1.2.5.RELEASE',
                'org.unbroken-dome.gradle-plugins:gradle-testsets-plugin:1.0.2'
        )
    }
}
 
apply plugin: 'java'
apply plugin: 'org.unbroken-dome.test-sets'
apply plugin: 'spring-boot'
 
sourceCompatibility = 1.8
targetCompatibility = 1.8
 
testSets {
    integrationTest { dirName = 'integration-test' }
}
 
project.integrationTest {
    outputs.upToDateWhen { false }
}
 
check.dependsOn integrationTest
integrationTest.mustRunAfter test
 
tasks.withType(Test) {
    reports.html.destination = file("${reporting.baseDir}/${name}")
}

 

After we have applied the Spring Boot Gradle plugin, we can

  • Package our application into an executable jar file.
  • Run our application by using the bootRun task.
  • Omit the version information information of Spring Boot dependencies.
  • Package our application into a war file.

Naturally we can also configure the Spring Boot Gradle plugin and customize the tasks that are used to run and package our application.

Getting the Required Dependencies

We can get the dependencies of our Spring Boot application by using so called starter POMs. The Spring Boot Reference Guide describes the starter POMs as follows:

Starter POMs are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy paste loads of dependency descriptors.

In other words, we have to select the correct starter POMs and add the starter POM dependencies into our Gradle build.

We can get the required dependencies by following these steps:

  1. Ensure that the dependencies are fetched from the central Maven2 repository.
  2. Add the spring-boot-starter-actuator dependency into the compile configuration. We need this dependency because it provides us a way to monitor our application when it is running.
  3. Add the spring-boot-starter-thymeleaf dependency into the compile configuration. We need this dependency because we want to create a web application that uses Thymeleaf as a templating engine.
  4. Add the spring-boot-starter-test dependency into the testCompile configuration. We need this dependency because we want to write both unit and integration tests for our web application.

The source code of our build.gradle file looks as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath(
                'org.springframework.boot:spring-boot-gradle-plugin:1.2.5.RELEASE',
                'org.unbroken-dome.gradle-plugins:gradle-testsets-plugin:1.0.2'
        )
    }
}
 
apply plugin: 'java'
apply plugin: 'org.unbroken-dome.test-sets'
apply plugin: 'spring-boot'
 
sourceCompatibility = 1.8
targetCompatibility = 1.8
 
repositories {
    mavenCentral()
}
  
dependencies {
    compile(
            'org.springframework.boot:spring-boot-starter-actuator',
            'org.springframework.boot:spring-boot-starter-thymeleaf'
    )
    testCompile('org.springframework.boot:spring-boot-starter-test')
}
 
testSets {
    integrationTest { dirName = 'integration-test' }
}
 
project.integrationTest {
    outputs.upToDateWhen { false }
}
 
check.dependsOn integrationTest
integrationTest.mustRunAfter test
 
tasks.withType(Test) {
    reports.html.destination = file("${reporting.baseDir}/${name}")
}

Running Our Spring Boot Application

We can run our Spring Boot application by using one of the following methods:

First, we can run our application without creating a jar file by using the bootRun task of the Spring Boot Gradle plugin. We should use this method during the development phase because it makes our static classpath resources (i.e. files found from the src/main/resources directory) reloadable.

In other words, if we use this method, we can make changes to these files when our Spring Boot application is running, and we can see these changes without restarting our application.

We can use this method by running the following command at the command prompt:

1
gradle clean bootRun

Second, we can package our application into an executable jar file and run the created jar file. We should use this method when we want to run our Spring Boot application on a remote server.

We can create an executable jar file by running the following command at the command prompt:

1
gradle clean build

This command creates the spring-boot-web-application.jar file to the build/libs directory. After we have copied this jar file to the remote server, we can start our application by running the following command at the command prompt:

1
java -jar spring-boot-web-application.jar

 

RESOURCES:

Spring boot web appication example

spring official

文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣()

REST API is today's requirements for Mobile Apps, Web Application or Desktop Application that need to connect with Database. That's why we need to create a step by step tutorial of building Java REST API server using Spring Boot and MongoDB. The data store in MongoDB server And accessible everywhere via Java REST API. Previously, we have to create REST API in different technology and framework using Grails and Node.js. Now, we are using Spring Boot for it. After all, you can compare which technology or framework that fits Your needs.

1. Generate a New Spring Boot Gradle Project

We assume that you have installed JDK 8, Gradle and IDE (Netbeans, Eclipse, STS or IntellijIdea). Next, we will create a new Spring Boot Gradle project using Spring Initializer. Just go to Spring Initializr web-based Spring project generator then fill The required frameworks and libraries.

After filling all fields, click Generate Project. It will automatically download the zipped project. Next, extract the zipped project to your java projects folder. On the project folder root, you will find `build.gradle` file for register dependencies, initially it Looks like this.

Buildscript { 
    Ext { 
        springBootVersion = '1.5.7.RELEASE' 
    } 
    Repositories { 
        mavenCentral() 
    } 
    Dependencies { 
        Classpath( "org.springframework.boot:spring-boot-gradle-plugin: ${springBootVersion} " ) 
    } 
} 

Apply plugin: 'java'  
apply plugin: 'eclipse'  
apply plugin: 'org.springframework.boot'
 
Group = 'com.spring'  
version = '0.0.1-SNAPSHOT' 
source Compatibility = 1.8 

Repositories { 
    mavenCentral() 
}


Dependencies { 
    Compile( 'org.springframework.boot:spring-boot-starter-data-mongodb' ) Compile 
    ( 'org.springframework.boot:spring-boot-starter-web' )
      test Compile( 'org.springframework.boot: Spring-boot-starter-test' ) 
}

Then open the other terminal then run MongoDB server. In current terminal go to newly extracted Spring Boot project folder then type this command to compile the application.

./gradlew compile 
Open and edit `src/resources/application.properties` then add this lines of strings. 
Spring.data.mongodb.database=springmongodb 
Spring.data.mongodb.host=localhost 
Spring.data.mongodb.port= 27017

2. Create Model or Entity Class

We are not accessing directly to MongoDB collections and fields but we have to access it via Java Object. For that, we have to create a new Java Class as a model or entity. If you are using Netbeans (similar with some IDE), right -click project name then click `New` then click `Java Class`.

Fill necessary fields like above screenshot then click Finish button. Netbeans will automatically open the newly created file, replace all codes with this.

Package com.spring.restapi.models;

Import org.springframework.data.annotation.Id;
  import org.springframework.data.mongodb.core.mapping.Document;

@Document (collection = "products" )
  public  class  Product  {
      @Id 
    String id; 
    String prodName; 
    String prodDesc; 
    Double prodPrice; 
    String prodImage;

    Public  Product ()  {
    }

    Public  Product (of prodName String, String prodDesc, prodPrice Double, String prodImage)  {
         the this .prodName of prodName =;
         the this .prodDesc = prodDesc;
         the this .prodPrice = prodPrice;
         the this .prodImage = prodImage;
    }

    Public String getId ()  {
         return id;
    }

    Public  void  setId (String id)  {
         this .id = id;
    }

    Public String getProdName ()  {
         return prodName;
    }

    Public  void  setProdName (String prodName)  {
         this .prodName = prodName;
    }

    Public String getProdDesc ()  {
         return prodDesc;
    }

    Public  void  setProdDesc (String prodDesc)  {
         this .prodDesc = prodDesc;
    }

    Public Double getProdPrice ()  {
         return prodPrice;
    }

    Public  void  setProdPrice (Double prodPrice)  {
         this .prodPrice = prodPrice;
    }

    Public String getProdImage ()  {
         return prodImage;
    }

    Public  void  setProdImage (String prodImage)  {
         this .prodImage = prodImage;
    }
}

That product class mapping to products collections of MongoDB which has 5 fields (id, prodName, prodDesc, prodPrice, prodImage). Each field has getter and setter.

3. Create a New Repository Interface for Product Model

Now, we need to create an interface for connecting Product model and controller. On Netbeans right-click project name on projects left panel then choose `New` then choose `Java Interface`.

Fill necessary fields like above screenshot then click Finish button. Netbeans will automatically open the new `ProductRepository.java` interface file. Replace all codes with this.

Package com.spring.restapi.repositories;

Import com.spring.restapi.models.Product;
  import org.springframework.data.repository.CrudRepository;

Public  interface  ProductRepository  extends  CrudRepository < Product , String > {
      @Override 
    Product findOne (String id) ;

    @Override 
    void  delete (Product deleted) ; 
}

We only add `findOne` and `delete` methods to the interface because the rest method already handled by `CrudRepository` of Spring Data MongoDB.

4. Create a New RESTful Controller for Accessing Product Data

Now, it's a time for RESTful Web Service (REST API) implementation by creating a new RESTful controller file. On the Netbeans right-click project name then click `New` then click `Java Class` again.

Fill necessary fields like above screen shot then click Finish button. Netbeans will automatically open the new `ProductController.java` class file. Replace all codes with this.

Package com.spring.restapi.controllers;

Import com.spring.restapi.models.Product;
  import com.spring.restapi.repositories.ProductRepository;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.web.bind.annotation.PathVariable;
  import org .springframework.web.bind.annotation.RequestBody;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RequestMethod;
  import org.springframework.web.bind.annotation.RestController;

@RestController 
public  class ProductController {

    @Autowired 
    ProductRepository productRepository;

    @RequestMapping (method=RequestMethod.GET, value= "/products" )
      public Iterable<Product> product() {
          return productRepository.findAll(); 
    }

    @RequestMapping (method=RequestMethod.POST, value= "/products" )
      public String save( @RequestBody Product product) { 
        productRepository.save(product);

        Return product.getId(); 
    }

    @RequestMapping (method=RequestMethod.GET, value= "/products/{id}" )
      public Product show( @PathVariable String id) {
          return productRepository.findOne(id); 
    }

    @RequestMapping (method=RequestMethod.PUT, value= "/products/{id}" )
      public Product update( @PathVariable String id, @RequestBody Product product) { 
        Product prod = productRepository.findOne(id); 
        If (product.getProdName () != null ) 
            prod.setProdName(product.getProdName()); 
        If (product.getProdDesc() != null ) 
            prod.setProdDesc(product.getProdDesc()); 
        If (product.getProdPrice() != null ) 
            prod.setProdPrice(product.getProdPrice()); 
        If(product.getProdImage() != null ) 
            prod.setProdImage(product.getProdImage()); 
        productRepository.save(prod); 
        Return prod; 
    }

    @RequestMapping (method=RequestMethod.DELETE, value= "/products/{id}" )
      public String delete ( @PathVariable String id) { 
        Product product = productRepository.findOne(id); 
        productRepository. delete (product);

        Return  "product deleted" ; 
    } 
}

 5.Run and Test the Spring Boot MongoDB RESTful Web Service

Let testing purpose, we use curl from terminal or command line. Let's start the server by type this command.

./gradlew bootRun

Open another terminal tab then type this command for post data to REST API.

Curl -i -X ​​POST -H "Content-Type: application/json" -d '{ "prodName" : "Dummy Product 1" , "prodDesc" : "The Fresh Dummy Product in The world part 1" , " prodPrice" : 100 , "prodImage" : "https://dummyimage.com/600x400/000/fff" }' localhost: 8080 /products

You will see the successful response like this.

HTTP/ 1.1  200  
Content-Type: text/plain;charset=UTF -8  
Content-Length: 24 
Date : Sun, 17 Sep 2017  10 : 14 : 39 GMT

59 be4b0fb1a2416a11a43c21

To get all product data type this command.

Curl -i -H "Accept: application/json" localhost:8080/products

You will see all data as JSON array like this.

HTTP/ 1.1  200  
Content-Type: application/json;charset=UTF -8 
Transfer-Encoding: chunked 
Date : Sun, 17 Sep 2017  10 : 17 : 08 GMT 

[{ "id" : "59be4b0fb1a2416a11a43c21" , "prodName" : " Dummy Product 1" , "prodDesc" : "The Fresh Dummy Product in The world part 1" , "prodPrice" : 100.0 , "prodImage" : "https:/ /dummyimage.com/600x400/000/fff"}]

To get single data, type this command.

Curl -i -H "Accept: application/json" localhost:8080/products/59be4b0fb1a2416a11a43c21

You will see the single object of JSON data.

HTTP/ 1.1  200  
Content-Type: application/json;charset=UTF -8 
Transfer-Encoding: chunked 
Date : Sun, 17 Sep 2017  10 : 17 : 08 GMT 

{ "id" : "59be4b0fb1a2416a11a43c21" , "prodName" : "Dummy Product 1" , "prodDesc" : "The Fresh Dummy Product in The world part 1" , "prodPrice" : 100.0 , "prodImage" : "https:// Dummyimage.com/600x400/000/fff"}

To update the specific data by ID type this command.

Curl -i -X ​​PUT -H "Content-Type: application/json"  -d  '{"prodPrice":220}'

You will see this response on successful update.

HTTP/ 1.1  200  
Content-Type: application/json;charset=UTF -8 
Transfer-Encoding: chunked 
Date : Sun, 17 Sep 2017  10 : 26 : 08 GMT 

{ "id" : "59be4b0fb1a2416a11a43c21" , "prodName" : "Dummy Product 1" , "prodDesc" : "The Fresh Dummy Product in The world part 1" , "prodPrice" : 220.0 , "prodImage" : "https:// Dummyimage.com/600x400/000/fff"}

To delete specific data by ID, type this command.

Curl - i -X DELETE localhost: 8080 /products/ 59 be4b0fb1a2416a11a43c21

You will see this response if successful delete.

HTTP/ 1.1  200 
Content-Type: text/plain;charset=UTF -8 
Content-Length: 15 
Date : Sun, 17 Sep 2017  10 : 28 : 38 GMT

Product deleted

 

RESOURCES:

SPRING BOOT REST 

Spring official

Spring boot rest tutorial

 

文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣()