Think Twice

Memorandum

Spring Boot

Josh のセッションをなぞる。

www.youtube.com

http://start.spring.io/でWeb,JPA,Thymeleaf,H2,Actuator,Remote ShellにチェックをいれてDownload

pom.xmlはこんな感じ。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-remote-shell</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

Reservationクラスを追加

@Entity
class Reservation {
    @Id
    @GeneratedValue
    private Long id;
    private String reservationName;

    @Override
    public String toString() {
        return "Reservation{" +
                "id=" + id +
                ", reservationName='" + reservationName + '\'' +
                '}';
    }

    Reservation() {
    }

    public Reservation(String reservationName) {
        this.reservationName = reservationName;
    }

    public Long getId() {
        return id;
    }

    public String getReservationName() {
        return reservationName;
    }
}

ReservationRepositoryインターフェースを追加

@RepositoryRestResource
interface ReservationRepository extends JpaRepository<Reservation, Long> {
    //select * from reservations where reservation_name = :rn
    Collection<Reservation> findByReservationName(@Param("rn") String rn);
}

DemoApplicationクラスにCommandLineRunner を追加。起動時に実行される。

    @Bean
    CommandLineRunner runner(ReservationRepository repository) {
        return args -> {
            Arrays.asList("Josh,Julie,Michael,Peter".split(","))
                    .forEach(n -> repository.save(new Reservation(n)));
            repository.findByReservationName("Julie").forEach(System.out::println);
            repository.findAll().forEach(System.out::println);
        };
    }

実行する。 f:id:mix-juice001:20150923220910p:plain H2に登録されていることがわかる。

RestControllerの追加

@RestController
class ReservationRestController {
    @Autowired
    private ReservationRepository reservationRepository;

    @RequestMapping("/reservations")
    Collection<Reservation> reservations() {
        return reservationRepository.findAll();
    }
}

実行する。

f:id:mix-juice001:20150923221300p:plain f:id:mix-juice001:20150923221428p:plain f:id:mix-juice001:20150923221529p:plain

MvcControllerの追加

@Controller
class ReservationMvcController {
    @Autowired
    ReservationRepository reservationRepository;

    @RequestMapping("/reservations.php")
    String page(Model model) {
        model.addAttribute("reservations", reservationRepository.findAll());
        return "reservations";
    }
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Bootiful Reservations</title>
</head>
<body>

<h1>Reservations</h1>

<div th:each="r : ${reservations}" >
    <b th:text="${r.id}">ID</b>
    <span th:text="${r.reservationName}">ReservationName</span>
</div>
</body>
</html>

実行する。

f:id:mix-juice001:20150923221851p:plain

Actuator

http://localhost:8080/metrics にアクセスすると、何回アクセスがあったのか等の情報を得ることができる。 f:id:mix-juice001:20150923222329p:plain

http://localhost:8080/traceにアクセス。 f:id:mix-juice001:20150923222244p:plain

http://localhost:8080/beans f:id:mix-juice001:20150923222438p:plain

http://localhost:8080/env f:id:mix-juice001:20150923222535p:plain

http://localhost:8080/dump f:id:mix-juice001:20150923222730p:plain

http://localhost:8080/mappings f:id:mix-juice001:20150923222736p:plain

jconsole

jconsole で見ることもできる

$ jconsole

f:id:mix-juice001:20150923223010p:plain "insecure connect"をクリックして f:id:mix-juice001:20150923223242p:plain f:id:mix-juice001:20150923223346p:plain

jmc

$ jmc

f:id:mix-juice001:20150924092013p:plain

Remote Shell

コンソールにShellでアクセスする場合のpasswordが出力されている。 f:id:mix-juice001:20150923223545p:plain

$ $ ssh -p 2000 user@127.0.0.1
Password authentication
Password:
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v1.2.6.RELEASE) on phantom.local
> help
Try one of these commands with the -h or --help switch:

NAME       DESCRIPTION
autoconfig Display auto configuration report from ApplicationContext
beans      Display beans in ApplicationContext
cron       manages the cron plugin
dashboard  a monitoring dashboard
egrep      search file(s) for lines that match a pattern
endpoint   Invoke actuator endpoints
env        display the term env
filter     a filter for a stream of map
java       various java language commands
jmx        Java Management Extensions
jul        java.util.logging commands
jvm        JVM informations
less       opposite of more
mail       interact with emails
man        format and display the on-line manual pages
metrics    Display metrics provided by Spring Boot
shell      shell related command
sleep      sleep for some time
sort       sort a map
system     vm system properties commands
thread     JVM thread commands
help       provides basic help
repl       list the repl or change the current repl

>
> endpoint list
requestMappingEndpoint
environmentEndpoint
healthEndpoint
beansEndpoint
infoEndpoint
metricsEndpoint
traceEndpoint
dumpEndpoint
autoConfigurationAuditEndpoint
configurationPropertiesReportEndpoint

> endpoint invoke healthEndpoint
{status=UP, diskSpace={status=UP, free=39115100160, threshold=10485760}, db={status=UP, database=H2, hello=1}}

>
> metrics

f:id:mix-juice001:20150923224709p:plain

> dashboard

f:id:mix-juice001:20150923224723p:plain

HealthIndicator を追加

    @Bean
    HealthIndicator gotoHealthIndecator() {
        return () -> Health.status("I <3 Chicago!").build();
    }

application.propertiesに設定を追加

server.port=8000
management.context-path=/admin
management.port=9000

http://localhost:8000/reservations

f:id:mix-juice001:20150923225045p:plain

http://localhost:9000/admin/health

f:id:mix-juice001:20150923225123p:plain

f:id:mix-juice001:20150923225322p:plain

make jar not war

$ mvn clean install
$ java -jar demo-0.0.1-SNAPSHOT.jar
$ export SERVER_PORT=8010
$ java -Dserver.port=8020 -jar demo-0.0.1.SNAPSHOT.jar