구글의 앱 엔진(http://appengine.appspot.com/)은 데이터를 저장할 때 비용이 발생합니다. SQL을 사용하려면 더 비쌉니다.

간단히 데이터를 저장하고 빼는 방법으로 DataStore API를 제공해줍니다. 그리고, 저장된 데이터는 관리자 웹 페이지를 통해서 확인할 수 있습니다.


저장하는 절차는 다음과 같습니다.

1. 환경에서 DatastoreService를 가져옵니다.

2. Key를 만듭니다. Key의 종류와 key 이름을 추가합니다.

3. 레코드는 Entity 클래스를 이용합니다.

4. entity에 key : value 형식으로 기록할 데이터를 입력합니다.

5. Datastore에 entity를 추가합니다.


private static final String KEY_KIND = "Game";

private static final String keyName = "games";


DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();


public void save(Game game) {

Key entityKey = KeyFactory.createKey(KEY_KIND, keyName);


Entity entity = new Entity(KEY_KIND, entityKey);


User firstUser = game.getFirstUser();

User secondUser = game.getSecondUser();


entity.setProperty("first", firstUser.getName());

entity.setProperty("firstchoice", firstUser.getChoice());

entity.setProperty("second", secondUser.getName());

entity.setProperty("secondchoice", secondUser.getChoice());


entity.setProperty("datetime", new Date());

entity.setProperty("ip", game.getIp());


datastore.put(entity);

}



관리자 페이지에서는 다음과 같이 화면이 제공됩니다.




데이터를 꺼내오는 방법은 다음과 같습니다.


1. Key를 만듭니다.

2. Query를 만들면서 정렬순서와 기준 항목을 정합니다.

3. Datastore에서 Query를 이용해서 데이터를 꺼냅니다.

4. Entity 목록을 처리합니다.

public List<Entity> fetchAll() {

Key entityKey = KeyFactory.createKey(KEY_KINDkeyName);

Query query = new Query(KEY_KIND, entityKey).addSort("datetime",

Query.SortDirection.DESCENDING);

List<Entity> games = datastore.prepare(query).asList(

FetchOptions.Builder.withLimit(5));


return games;

}




+ Recent posts