Archive for the ‘Tomcat’ Category
Configurar Datasource no Tomcat 6
Edite o arquivo server.xml, e procure pelo context da sua aplicação, caso não exista, esta é uma boa hora para criar.
Após extraído, este deve ser colocado em: %TOMCAT%/lib
Algumas informações a respeito da configuração:
source: diretorio root da aplicacao
Edite o arquivo web.xml da sua aplicação e inclua no final deste, antes do uma referencia para o DataSource recen configurado:
Se ainda não tiver, baixe as Taglibs (http://jakarta.apache.org/site/downloads/downloads_taglibs-standard.cgi) copie os arquivos: jstl.jar e standart.jar para o diretório WEB-INF/lib de sua aplicação.
No banco de dados recem criado cria uma tabela chamada com o seguinte comando:
Insira alguns registros apenas para fins de teste.
Crie um jsp com o seguinte conteúdo na home de sua aplicação:
Inicie o Tomcat e acesse a página criada.
A página deverá mostrar todos os registros que constam na tabela.
O driver de conexão do MySQL pode ser obtido no site do produto. (http://dev.mysql.com/downloads/connector/j/5.1.html)<Context docBase="ProjetoWEB1" path="/projetoweb1" reloadable="true" source="org.eclipse.jst.jee.server:ProjetoWEB1"> <Resource name="jdbc/ProjetoWEB01" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="tomcatjpauser" password="tomcatjpauser" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/tomcatjpa?autoReconnect=true" /> </Context>
Após extraído, este deve ser colocado em: %TOMCAT%/lib
Algumas informações a respeito da configuração:
Context (server.xml)
path: url que servira de acesso no browsersource: diretorio root da aplicacao
Resource (serverl.xml)
Configuração do DataSource, este no caso está configurado para acessar um banco de dados no MySQL.Edite o arquivo web.xml da sua aplicação e inclua no final deste, antes do uma referencia para o DataSource recen configurado:
<resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/ProjetoWEB01</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
Testando
Se ainda não tiver, baixe as Taglibs (http://jakarta.apache.org/site/downloads/downloads_taglibs-standard.cgi) copie os arquivos: jstl.jar e standart.jar para o diretório WEB-INF/lib de sua aplicação.
No banco de dados recem criado cria uma tabela chamada com o seguinte comando:
CREATE TABLE testdata ( id int(11) NOT NULL AUTO_INCREMENT, foo varchar(25) DEFAULT NULL, bar int(11) DEFAULT NULL, PRIMARY KEY (id) )
Insira alguns registros apenas para fins de teste.
Crie um jsp com o seguinte conteúdo na home de sua aplicação:
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <sql:query var="rs" dataSource="jdbc/ProjetoWEB01"> select id, foo, bar from testdata </sql:query> <html> <head> <title>DB Test</title> </head> <body> <h2>Results</h2> <c:forEach var="row" items="${rs.rows}"> Foo ${row.foo}<br/> Bar ${row.bar}<br/> </c:forEach> </body> </html>
Inicie o Tomcat e acesse a página criada.
A página deverá mostrar todos os registros que constam na tabela.
Tomcat + Ubuntu antes de iniciar….
Após baixar o Tomcat e descompacta-lo pode ocorrer o seguinte erro quando tentar inicia-lo atraves do comando startup.sh:
Vá para o diretorio bin do tomcat e de permissao 777 ou +x para todos os arquivos .sh:
The BASEDIR environment variable is not defined correctly
Vá para o diretorio bin do tomcat e de permissao 777 ou +x para todos os arquivos .sh:
sudo chmod 777 *.sh
Apache + JBoss com mod_jk
1 - Instale o Apache
2 - Instale o JBoss
3 - Instale o mod_jk (download em: http://tomcat.apache.org/download-connectors.cgi)
Faça o download do modulo e copie-o no diretorio de modules do apache.
4 - Configure o mod_jk no Apache
Crie o arquivo: mod-jk.conf no diretorio conf do apache e insira o conteudo:
5 - Inclua a chamada para o mod-jk.conf no httpd.conf do Apache:
Altere o arquivo httpd.conf do Apache, inserindo a linha:
Include conf/mod-jk.conf
6 - Crie o arquivo workers.properties
Esclarecimentos:
(1) You should only set the connection_pool_size if the number of allowed connection to the Httpd is higher than maxThreads in server.xml
If you specify worker.loadbalancer.sticky_session=Off, each request will be load balanced between node1 and node2. But when a user opens a Session on one server, it is a good idea to always forward this user’s requests to the same server. Otherwise the user’s session data would need to be synchronized between both servers. This is called a “sticky session”, as the client is always using the same server he reached on his first request. Session stickiness is enabled by default.
Side Note: a non-loadbalanced setup with a single node required the “worker.list=node1″ entry before mod_jk would function correctly. Without this setting I would only get a 500 error and no other useful messages in log or otherwise. -Harlequin516
Side Note: I tried both loadbalanced and single node methods on Fedora 4. Both setups causing jk.shm errno=13 and jk-runtime-status errno=13 in the mod_jk.log. Could only get 500 errors. As a last resort disabled selinux on apache server. Restarted service and connection was made first try. -paulbrown
7 - Criar o arquivo de mapeamento (uriworkermap.properties)
Crie o arquivo uriworkermap.properties no diretorio conf do Apache.
Esclarecimento: Isso fara com que toda requisição feita ao apache a /web-console e jmx-console seja direcionada para o JBoss.
8 - Configuração do Tomcat do JBoss
Altere o arquivo: server.xml, localize o trecho:
inclua o jvmRoute=”node1″
Verifique se o conector AJP1.3 nao esta comentado:
Altere o arquivo jboss-service.xml fazendo com q o atributo UseJK seja igual a true:
9 - Start
Inicie o Apache e o JBoss e acesse: http://localhost/web-console
Fonte: Jboss-Wiki
2 - Instale o JBoss
3 - Instale o mod_jk (download em: http://tomcat.apache.org/download-connectors.cgi)
Faça o download do modulo e copie-o no diretorio de modules do apache.
4 - Configure o mod_jk no Apache
Crie o arquivo: mod-jk.conf no diretorio conf do apache e insira o conteudo:
# Load mod_jk module # Specify the filename of the mod_jk lib LoadModule jk_module modules/mod_jk.so # Where to find workers.properties JkWorkersFile conf/workers.properties # Where to put jk logs JkLogFile logs/mod_jk.log # Set the jk log level [debug/error/info] JkLogLevel info # Select the log format JkLogStampFormat "[%a %b %d %H:%M:%S %Y]" # JkOptions indicates to send SSK KEY SIZE # Note: Changed from +ForwardURICompat. # See http://tomcat.apache.org/security-jk.html JkOptions +ForwardKeySize +ForwardURICompatUnparsed -ForwardDirectories # JkRequestLogFormat JkRequestLogFormat "%w %V %T" # Mount your applications JkMount /application/* loadbalancer # You can use external file for mount points. # It will be checked for updates each 60 seconds. # The format of the file is: /url=worker # /examples/*=loadbalancer JkMountFile conf/uriworkermap.properties # Add shared memory. # This directive is present with 1.2.10 and # later versions of mod_jk, and is needed for # for load balancing to work properly # Note: Replaced JkShmFile logs/jk.shm due to SELinux issues. Refer to # https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=225452 JkShmFile run/jk.shm # Add jkstatus for managing runtime data <location> JkMount status Order deny,allow Deny from all Allow from 127.0.0.1 <location>
5 - Inclua a chamada para o mod-jk.conf no httpd.conf do Apache:
Altere o arquivo httpd.conf do Apache, inserindo a linha:
Include conf/mod-jk.conf
6 - Crie o arquivo workers.properties
# Define list of workers that will be used # for mapping requests # The configuration directives are valid # for the mod_jk version 1.2.18 and later # worker.list=loadbalancer,status # # Define Node1 # modify the host as your host IP or DNS name. worker.node1.port=8009 worker.node1.host=localhost worker.node1.type=ajp13 worker.node1.lbfactor=1 # worker.node1.connection_pool_size=10 (1) # # Define Node2 # modify the host as your host IP or DNS name. worker.node2.port=8009 worker.node2.host=localhost worker.node2.type=ajp13 worker.node2.lbfactor=1 # worker.node1.connection_pool_size=10 (1) # # Load-balancing behaviour worker.loadbalancer.type=lb worker.loadbalancer.balance_workers=node1,node2 # # Status worker for managing load balancer worker.status.type=status
Esclarecimentos:
(1) You should only set the connection_pool_size if the number of allowed connection to the Httpd is higher than maxThreads in server.xml
If you specify worker.loadbalancer.sticky_session=Off, each request will be load balanced between node1 and node2. But when a user opens a Session on one server, it is a good idea to always forward this user’s requests to the same server. Otherwise the user’s session data would need to be synchronized between both servers. This is called a “sticky session”, as the client is always using the same server he reached on his first request. Session stickiness is enabled by default.
Side Note: a non-loadbalanced setup with a single node required the “worker.list=node1″ entry before mod_jk would function correctly. Without this setting I would only get a 500 error and no other useful messages in log or otherwise. -Harlequin516
Side Note: I tried both loadbalanced and single node methods on Fedora 4. Both setups causing jk.shm errno=13 and jk-runtime-status errno=13 in the mod_jk.log. Could only get 500 errors. As a last resort disabled selinux on apache server. Restarted service and connection was made first try. -paulbrown
7 - Criar o arquivo de mapeamento (uriworkermap.properties)
Crie o arquivo uriworkermap.properties no diretorio conf do Apache.
# Simple worker configuration file # # # Mount the Servlet context to the ajp13 worker /jmx-console=loadbalancer /jmx-console/*=loadbalancer /web-console=loadbalancer /web-console/*=loadbalancer
Esclarecimento: Isso fara com que toda requisição feita ao apache a /web-console e jmx-console seja direcionada para o JBoss.
8 - Configuração do Tomcat do JBoss
Altere o arquivo: server.xml, localize o trecho:
<Engine name="jboss.web" defaulthost="localhost" jvmroute="node1"> . </Engine>
inclua o jvmRoute=”node1″
Verifique se o conector AJP1.3 nao esta comentado:
<Connector port="8009" address="${jboss.bind.address}">
emptySessionPath="true" enableLookups="false" redirectPort="8443"
protocol="AJP/1.3"/></Connector>Altere o arquivo jboss-service.xml fazendo com q o atributo UseJK seja igual a true:
<attribute name="UseJK">true</attribute>
9 - Start
Inicie o Apache e o JBoss e acesse: http://localhost/web-console
Fonte: Jboss-Wiki
Tomcat Embedded
No último dia eu estava desenvolvendo uma aplicação de missão critica com alguns requisitos bem próprios desse tipo de applicativo:
Ambos os requisitos mais “cabeludos” achei uma solução:
O Segundo não foi tão fácil, mas foi muito legal, nas proximas linhas, vou descrever como colocar um servidor Tomcat junto com sua applicação, da mesma maneira que se faz com o Derby DB ou o HBSQLDB.
Read the rest of this entry »
- - Não pode parar nunca, nem para alteraçoes em parametros;
- - Precisa reportar status constantemente;
Ambos os requisitos mais “cabeludos” achei uma solução:
- - Todos os parametros (ou a grande maioria) nao poderiam ser cacheados
- - Aplicação web que servisse de console para a aplicação.
O Segundo não foi tão fácil, mas foi muito legal, nas proximas linhas, vou descrever como colocar um servidor Tomcat junto com sua applicação, da mesma maneira que se faz com o Derby DB ou o HBSQLDB.
Read the rest of this entry »