用laggom创建一个简单的模拟json服务

时间:2019-04-18 12:42:15

标签: java lagom

拉各姆(Lagom)似乎很有趣,但是我很难使事情变得简单。似乎我不了解它的工作原理和世界例子,尽管它起作用,但我不知道如何使用它。

我正在尝试创建一个简单的静态服务,该服务的标头带有两个参数并生成一个json对象。例如,在MyService.java中,我有:

public interface BookService extends Service {

    ServiceCall<NotUsed, String> getAllBook();

    /**
     * @return
     */
    @Override
    default Descriptor descriptor() {

        return named("book").withCalls(
            restCall(GET, "/api/get-all-book", this::getAllBook)
        ).withAutoAcl(true);
    }
}

然后在BookServiceImpl中,我有:

public class BookServiceImpl implements BookService {

    private final PersistentEntityRegistry persistentEntityRegistry;

    /**
     * @param registry
     * @param readSide
     * @param session
     */
    @Inject
    public BookServiceImpl(final PersistentEntityRegistry registry, ReadSide readSide, CassandraSession session) {
        this.persistentEntityRegistry = registry;

        persistentEntityRegistry.register(BookEntity.class);
        readSide.register(BookEventProcessor.class);
    }


    @Override
    public ServiceCall<NotUsed, String> getAllBook() {
        return request -> {

            JSONObject myBook= new JSONObject();
            myBook.put("name","BookName");
            myBook.put("description","A description");
            myBook.put("price","$16");
            myBook.put("status","available");

            //how do I return JSONBject.toString()
        };
    }
}

然后如何放置标头参数?一些说明基础知识的文档将非常有帮助。

预先感谢

1 个答案:

答案 0 :(得分:0)

您需要创建一个实际执行JSON的POJO类。通过在服务实现中使用lombok软件包:

package mybook;


import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Value;

import javax.annotation.concurrent.Immutable;

@Value
@Builder
@Immutable
@JsonDeserialize
@AllArgsConstructor
public class Book {
    String name; 
    String description; 
    String value; 
    String status;
}

然后投入使用:

public interface BookService extends Service {

    ServiceCall<NotUsed, Book> getAllBook();

    /**
     * @return
     */
    @Override
    default Descriptor descriptor() {

        return named("book").withCalls(
            restCall(GET, "/api/get-all-book", this::getAllBook)
        ).withAutoAcl(true);
    }
}

然后在实现中:

public class BookServiceImpl implements BookService {

    @Override
    public ServiceCall<NotUsed, Book> getAllBook() {
        return request -> {
            Book myBook =     Book.builder().
                                name("BookName").
                                description("A description").
                                price("16€").
                                status("available").build();

            return completedFuture(myBook);
        };
    }
}