2016年6月9日木曜日

Go Lang mapのキーが存在しているか確認

  • このエントリーをはてなブックマークに追加


Go Lang mapのキーが存在しているか確認 GO言語マップに特定のキーがあるかどうかを確認するサンプルコードをメモします。
package main
import "fmt"

func main() {
dict := map[string]int{
    "foo": 1,
}

//存在する
if val, ok := dict["foo"]; ok {
    fmt.Printf("foo exists. The value is %#v", val)
}

//存在しない
if _, ok := dict["foo"]; ok {
    fmt.Printf("foo not exists")
}

2016年5月24日火曜日

golang 時間を引数としてプログラムに渡す

  • このエントリーをはてなブックマークに追加


golang 時間を引数としてプログラムに渡す golangプログラムで引数で指定された時間でSleepしたくて、いろいろはまってました。

Code

//整数を受け取って、Millisecondの倍数の時間でスリープ、既定は1000ミリ秒

multipleOfMS := flag.Int("m", 1000, "msの倍数")
flag.Parse()
time.Sleep(multipleOfMS * time.Millisecond)

Error

invalid operation: multipleOfMS * time.Millisecond (mismatched types *int and time.Duration)

Int型をtime.durationに変更

 multipleOfMS := flag.Int("m", 1000, "msの倍数")
flag.Parse()
time.Sleep(time.Duration(multipleOfMS) * time.Millisecond)

やはりエラー

cannot convert multipleOfMS (type *int) to type time.Duration
いろいろ調べてflag.Durationというのがあってこっちを使う
multipleOfMS := flag.Duration("m", 1 * time.Second, "-m=2sのように設定")
flag.Parse()
time.Sleep(*multipleOfMS)

実行

//5秒sleep
go run main.go -m=5s
//500ミリ秒sleep
go run main.go -m=500ms

2016年5月20日金曜日

Mysql backup

  • このエントリーをはてなブックマークに追加


Mysql backup Mysql DB バックアップ用シェルをメモしておきます。

backup shell

#!/bin/bash

PATH=/usr/local/sbin:/usr/bin:/bin
BKUPDIR=/home/backup/mysqlhot
DATE=`date +%Y%m%d%H%S`
DATE1=`date +%Y%m%d`

sudo rm  -rf $BKUPDIR
mkdir -p $BKUPDIR

# performance_schemaをスキップ
DBLIST=`sudo ls -p /var/lib/mysql | grep / | grep -v performance_schema | tr -d /`

for dbname in $DBLIST
        do
        table_count=`mysql -u root -B -e "show tables" $dbname|wc -l`
        [ $table_count -ne 0 ] &&
        sudo mysqlhotcopy $dbname -u admin -p admin $BKUPDIR | logger -t mysqlhotcopy
done

sudo tar czvf /home/backup/bkup/mysql_dbs.$DATE.tar.gz /home/backup/mysqlhot
sudo /usr/bin/find /home/backup/bkup/ -name "*.tar.gz" -mtime +4 -exec rm {} \;

problem 1

以下のようなエラーが出力されました。
$ mysqlhotcopy  -u root mysqlhot/
install_driver(mysql) failed: Can't locate DBD/mysql.pm in @INC (@INC contains: /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at (eval 12) line 3.
Perhaps the DBD::mysql perl module hasn't been fully installed,
or perhaps the capitalisation of 'mysql' isn't right.
Available drivers: DBM, ExampleP, File, Gofer, Proxy, SQLite, Sponge.
 at /usr/bin/mysqlhotcopy line 200

solution

 $ sudo yum install "perl(DBD::mysql)"

problem 2

DBD::mysql::db do failed: SELECT, LOCK TABLES command denied to user 'admin'@'localhost' for table 'accounts' at /usr/bin/mysqlhotcopy line 523.

solution

performance_schema DBのバックアップをスキップする

2016年5月14日土曜日

MAC golang インストールとGOPATH設定

  • このエントリーをはてなブックマークに追加


MAC golang インストールとGOPATH設定 仕事でGOを使って、クライアントにWebsocketでメッセージをPushするサービスを開発しています。
GOのmacへのインストールとGOPATHの設定をメモします

install

$ brew install go
インストール先が/usr/local/goとなるはずです。

GO workspace作成

GOのworkspace(どこでもいい)を作成して、GOのソースコードとパッケージ、実行可能なバイナリファイルを格納します。
一般的に以下のように配置します。
例:…work/
.../gowork/src
.../gowork/pkg
.../gowork/bin

GOPATH設定

GO workspaceを決めたので、GOPATHを設定します。workspaceのbinとGoのインストール先binも合わせて追加しておきます。
$ mkdir $HOME/c-ye/gowork
$ vi ~/.bash_profile

export GOPATH=$HOME/c-ye/gowork
PATH=$PATH:$GOPATH/bin:/usr/local/go/bin
これで$HOME/c-ye/goworkの下にプロジェクトごとにソースを配置します。
また、godepをインストールした場合は
$ go get github.com/tools/godep
$HOME/c-ye/goworkのフォルダ中身が以下のようになる。
bin
    godep  #実行可能
pkg
    darwin_amd64
        github.com/tools/godep/
src
    github.com/tools/godep/
        diff.go
        go.go
        main.go
        ......
    testGO/      #自分のプロジェクト
        main.go 
とりあえずこんな感じです。詳しいはこちらを
https://golang.org/doc/code.html#Overview

2016年2月11日木曜日

Play! 2.4.4 + Scala 2.11.6 バイナリ、Jar、warファイルを生成する

  • このエントリーをはてなブックマークに追加


最近、Play 2.4.4 + Scala 2.11.6でプログラムを書いていて、アプリのデプロイ方法色々調べてたので、binary, jar, war ファイルの方法をご紹介します。

バイナリファイル

これは推奨されるやり方だそうです。javaさえインストールしていればそのまま実行できます。
構成ファイルbuild.sbtやplugin.sbtファイルに特別な設定入れなくても大丈夫です。
プロジェクトフォルダ(myApp)に入って、activator distを実行する
PS C:\myApp> .\activator dist
image_thumb3
これで. C:\myApp\target\universal\myapp-1.0-SNAPSHOT.zip ファイルが生成される。
zipファイルを解凍して、以下のようなフォルダ構造になります。
image_thumb5
bin フォルダの下に、2つの実行ファイルがあります。myappはLinux版、myapp.batはWindows版になります。
image_thumb7
ファイルを実行する
C:\myApp\target\universal\myapp-1.0-SNAPSHOT\bin> .\myapp 
デフォルトポート9000を他のポートに変更することもできます。
C:\myApp\target\universal\myapp-1.0-SNAPSHOT\bin> .\myapp “-Dhttp.port=8080”
※注意:ダブルクオーテーションが必要です。ない場合は、以下の様なエラーが表示される
PS C:\myApp\target\universal\myapp-1.0-SNAPSHOT\bin> .\myapp -Dhttp.port=80 Bad root server path: C:\myApp\target\universal\myapp-1.0-SNAPSHOT\bin\8080
image_thumb9

JARファイル

Jarを生成する場合は、sbt-assemblyプラグインが必要です。
build.sbtファイルに以下のコードを追記する。
//configuration for activator assembly : start
import AssemblyKeys._
assemblySettings
mainClass in assembly := Some("play.core.server.NettyServer")
fullClasspath in assembly += Attributed.blank(PlayKeys.playPackageAssets.value)
//skip test test in assembly := {}
jarName in assembly := "myApp.1.0-SNAPSHOT.jar"
mergeStrategy in assembly := {   case PathList("javax", "servlet", xs @ _*)         => MergeStrategy.first   case PathList(ps @ _*) if ps.last endsWith ".properties" => MergeStrategy.first   case PathList(ps @ _*) if ps.last endsWith ".xml" => MergeStrategy.first   case PathList(ps @ _*) if ps.last endsWith ".types" => MergeStrategy.first   case PathList(ps @ _*) if ps.last endsWith ".class" => MergeStrategy.first   case "application.conf"                            => MergeStrategy.concat   case "unwanted.txt"                                => MergeStrategy.discard   case x =>     val oldStrategy = (mergeStrategy in assembly).value     oldStrategy(x) }
//configuration for activator assembly : end
......
project/plugins.sbtに以下を追記する
//configuration for activator assembly
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.11.2") 
バージョンを0.11.2にしてますが、sbtのバージョンに合わせる必要です。以下をご参照ください。
https://github.com/sbt/sbt-assembly/tree/0.11.2

activator assemblyを実行する
PS C:\myApp> .\activator assembly[info] Loading project definition from C:\myApp\project
[info] Set current project to myApp (in build file:/C:/myApp/)
Warning: node.js detection failed, sbt will use the Rhino based Trireme JavaScript engine instead to run JavaScript asse
ts compilation, which in some cases may be orders of magnitude slower than using node.js.
[info] Including from cache: play-cache_2.11-2.4.6.jar
[info] Including from cache: xml-apis-1.4.01.jar
[info] Including from cache: ehcache-core.jar
[info] Including from cache: jta-1.1.jar
[info] Including from cache: play-ws_2.11-2.4.6.jar
[info] Including from cache: scala-library.jar
[info] Including from cache: guice.jar
[info] Including from cache: twirl-api_2.11.jar
[info] Including from cache: scala-reflect-2.11.6.jar
[info] Including from cache: jackson-core.jar
[info] Including from cache: commons-lang3.jar
[info] Including from cache: jackson-annotations.jar
[info] Including from cache: guava.jar
[info] Including from cache: javax.inject.jar
[info] Including from cache: aopalliance.jar
[info] Including from cache: jackson-databind.jar
[info] Including from cache: scala-xml_2.11-1.0.1.jar
[info] Including from cache: jackson-datatype-jdk8.jar
[info] Including from cache: play-server_2.11-2.4.6.jar
[info] Including from cache: async-http-client.jar
[info] Including from cache: signpost-core-1.2.1.2.jar
[info] Including from cache: guice-assistedinject.jar
[info] Including from cache: play_2.11-2.4.6.jar
[info] Including from cache: play-netty-server_2.11-2.4.6.jar
[info] Including from cache: netty.jar
[info] Including from cache: jackson-datatype-jsr310.jar
[info] Including from cache: build-link-2.4.6.jar
[info] Including from cache: play-exceptions-2.4.6.jar
[info] Including from cache: play-netty-utils-2.4.6.jar
[info] Including from cache: signpost-commonshttp4-1.2.1.2.jar
[info] Including from cache: slf4j-api.jar
[info] Including from cache: javassist.jar
[info] Including from cache: jul-to-slf4j.jar
[info] Including from cache: netty-http-pipelining.jar
[info] Including from cache: httpcore.jar
[info] Including from cache: play2-war-core-servlet30_2.11-1.4-beta1.jar
[info] Including from cache: play-iteratees_2.11-2.4.6.jar
[info] Including from cache: httpclient.jar
[info] Including from cache: play2-war-core-common_2.11-1.4-beta1.jar
[info] Including from cache: commons-logging-1.1.1.jar
[info] Including from cache: play-jdbc_2.11-2.4.6.jar
[info] Including from cache: scala-stm_2.11-0.7.jar
[info] Including from cache: play-jdbc-api_2.11-2.4.6.jar
[info] Including from cache: mariadb-java-client-1.3.4.jar
[info] Including from cache: jcl-over-slf4j.jar
[info] Including from cache: bonecp.jar
[info] Including from cache: config.jar
[info] Including from cache: HikariCP.jar
[info] Including from cache: scala-parser-combinators_2.11-1.0.1.jar
[info] Including from cache: anorm_2.11-2.4.0.jar
[info] Including from cache: play-json_2.11-2.4.6.jar
[info] Including from cache: anorm-tokenizer_2.11-2.4.0.jar
[info] Including from cache: h2.jar
[info] Including from cache: scala-arm_2.11-1.4.jar
[info] Including from cache: logback-core.jar
[info] Including from cache: tyrex.jar
[info] Including from cache: scala-continuations-library_2.11-1.0.1.jar
[info] Including from cache: play-functional_2.11-2.4.6.jar
[info] Including from cache: play-datacommons_2.11-2.4.6.jar
[info] Including from cache: logback-classic.jar
[info] Including from cache: bootstrap-3.3.1.jar
[info] Including from cache: joda-time.jar
[info] Including from cache: jquery-1.11.1.jar
[info] Including from cache: joda-convert.jar
[info] Including: myapp_2.11-1.0-SNAPSHOT-web-assets.jar
[info] Including from cache: akka-actor_2.11.jar
[info] Including from cache: akka-slf4j_2.11.jar
[info] Including from cache: commons-codec.jar
[info] Including from cache: xercesImpl-2.11.0.jar
[info] Checking every *.class/*.jar file's SHA-1.
[info] Merging files...
[warn] Merging 'META-INF\DEPENDENCIES' with strategy 'discard'
[warn] Merging 'META-INF\MANIFEST.MF' with strategy 'discard'
[warn] Merging 'META-INF\services\com.fasterxml.jackson.databind.Module' with strategy 'filterDistinctLines'
[warn] Merging 'META-INF\services\java.sql.Driver' with strategy 'filterDistinctLines'
[warn] Merging 'org\apache\commons\logging\Log.class' with strategy 'first'
[warn] Merging 'org\apache\commons\logging\LogConfigurationException.class' with strategy 'first'
[warn] Merging 'org\apache\commons\logging\LogFactory.class' with strategy 'first'
[warn] Merging 'org\apache\commons\logging\impl\NoOpLog.class' with strategy 'first'
[warn] Merging 'org\apache\commons\logging\impl\SimpleLog$1.class' with strategy 'first'
[warn] Merging 'org\apache\commons\logging\impl\SimpleLog.class' with strategy 'first'
[warn] Merging 'reference.conf' with strategy 'concat'
[warn] Strategy 'concat' was applied to a file
[warn] Strategy 'discard' was applied to 2 files
[warn] Strategy 'filterDistinctLines' was applied to 2 files
[warn] Strategy 'first' was applied to 6 files
[info] SHA-1: ed00c338faad479d3f2a17dc26844c4de9945297
[info] Packaging C:\myApp\target\scala-2.11\myApp.1.0-SNAPSHOT.jar ...
[info] Done packaging.
[success] Total time: 164 s, completed 2016/02/11 16:17:24
packagingが終わったら、C:\myApp\target\scala-2.11\myApp.1.0-SNAPSHOT.jar というファイルが生成され、実行できます。
PS C:\myApp\target\scala-2.11> java -jar .\myApp.1.0-SNAPSHOT.jar

WARファイル

http://terrence.logdown.com/posts/262781-play-framework-project-to-build-war-files-to-tomcat-perform
WARの場合も、build.sbtとproject/plugins.sbtを編集する必要があります。
build.sbt
……
//configuration for activator war : start import com.github.play2war.plugin._
Play2WarPlugin.play2WarSettings
//3.1 for tomcat 8,Wildfly 8, Glassfish 4, Jetty 9 //3.0 for tomcat 7,JBoss 7, JBoss EAP 6, Glassfish 3, Jetty 8 Play2WarKeys.servletVersion := "3.0"
//configuration for activator war : end
……
libraryDependencies ++= Seq(   jdbc,   cache,   ws,   specs2 % Test,   "org.mariadb.jdbc" % "mariadb-java-client" % "1.3.4",   "com.typesafe.play" %% "anorm" % "2.4.0",   "org.webjars" % "bootstrap" % "3.3.1"  //configuration for activator war )
……
project/plugins.sbt
//configuration for activator war
addSbtPlugin("com.github.play2war" % "play2-war-plugin" % "1.4-beta1")
https://github.com/play2war/play2-war-plugin/wiki/Configuration
プラグインのバージョン設定は上記URLをご参照ください。
activator warを実行する
PS C:\myApp> .\activator war
[info] Loading project definition from C:\myApp\project
[info] Set current project to myApp (in build file:/C:/myApp/)
[info] Wrote C:\myApp\target\scala-2.11\myapp_2.11-1.0-SNAPSHOT.pom
Warning: node.js detection failed, sbt will use the Rhino based Trireme JavaScript engine instead to run JavaScript asse
ts compilation, which in some cases may be orders of magnitude slower than using node.js.
[info] Build WAR package for servlet container: 3.0
[info] Packaging C:\myApp\target\myapp-1.0-SNAPSHOT.war ...
[info] Packaging done.
[success] Total time: 3 s, completed 2016/02/11 16:45:53
targetフォルダにwarファイルが生成されて、それをtomcatなどで配置すれば実行できるはずです。