wxPython学习笔记(二) 创建基本的wxPython程序

0 评论  

创建基本的wxPython程序

  • 主题:

    • 创建一个基本的wxPython程序
    • 将这个程序打造成一个简单的文本编辑器

本节将介绍如何使用wxPython构建一个小型的文本编辑器。通过这个看似复杂的任务你将会体验到wxPython有多方便和简单。

概述

  • 每当大家提前GUI编程的时候,总是会牵扯到窗体,菜单,鼠标,图标等等。或许你的第一感觉wx.Windows就对应一个显示在屏幕上的窗口,但你错了,在wxPython中,wx.Window表示任意可以显示在屏幕上的东西的对象,wx.Window这个类是所有屏幕上可见的对象的基类,诸如输入框,下拉列表都是由它派生而来。屏幕上的可见对象都有一些共同的属性和行为,比如位置,尺寸,是否可见,是否处于输入焦点等等,这些在wx.Window里面都有定义。 所以如果你要找一个类来表示窗口,就应该用继承自wx.Window的wx.Frame而不是wx.Window. wx.Frame实现了所有与屏幕相关的行为和属性(当然如果wx.Frame位于MDI中则另当别论) .要创建一个窗体,可以用wx.Frame,也可以用其子类如wx.Dialog,但不能再按照思维定势去想wx.Window了。

一个简单的例子

添加编辑控件

要编写一个文本编辑器,首先当然需要一个编辑控件,如下:
import wx
class MainWindow(wx.Frame):
""" We simply derive a new class of Frame. """
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(200,100))
self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
self.Show(True)
app = wx.PySimpleApp()
frame=MainWindow(None, wx.ID_ANY, 'Small editor')
app.MainLoop()
  • (需要注意的是这里我们定义了一个继承自wx.Frame的类,在类的初始化方法最后调用了父类的show方法,这也就不需要在额外调用show方法。) 如你所见,这段代码还是非常简洁, 我们所做的只是继承了一个wxFrame然后覆写了它的构造函数,在构造函数中新建一个简单的文本编辑框控件,就这样,就有了如下的效果图:

添加菜单栏

多数你所见到的GUI程序都有一个菜单栏和一个状态栏,下面就开始添加这两个组件:
import wx
ID_ABOUT=101
ID_EXIT=110
class MainWindow(wx.Frame):
def __init__(self,parent,id,title):
wx.Frame.__init__(self,parent,wx.ID_ANY, title, size = (300,200))
self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
self.CreateStatusBar() # A Statusbar in the bottom of the window
# Setting up the menu.
filemenu= wx.Menu()
filemenu.Append(ID_ABOUT, "&About"," Information about this program")
filemenu.AppendSeparator()
filemenu.Append(ID_EXIT,"E&xit"," Terminate the program")
# Creating the menubar.
menuBar = wx.MenuBar()
menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.
self.Show(True)
app = wx.PySimpleApp()
frame = MainWindow(None, -1, "Sample editor")
app.MainLoop()

  • 菜单有了,但是点击菜单却没有任何反应,下面添加事件处理:

实战事件处理

  • 对事件做处理就是人们常说的事件处理,wxPython的一大特色就是在事件处理上有极高的灵活性。接下来我们将添加一下实战的代码,这些代码或许已经超越了基于前面一章的理解能力,所以对他们的讨论将放到后续章节。 简单的说,一个事件就是一条发送到wxPython得消息告知有什么事情发生了,需要处理了 [6].通常来说,你所要做的就是把这个事件连接到一个特定的方法,让这个方法去处理,仅仅需要调用

    EVT_*. (Also see Avoiding EVT_MENU.) 方法,如下:

    EVT_MENU(self, ID_ABOUT, self.OnAbout)
    这个函数的作用在将对菜单ID 为ID_ABOUT的事件都扔给self.OnAbout去处理。

    self.OnAbout函数可能就像下面这个样子:

    def OnAbout(self, event)

    OnAbout的参数是event对象,它所做的就是在事件发生时:

  • 跳过这个事件, 让事件在事件处理周期里转到另外的处理程序。
  • 或者处理这个事件,事件消息在被程序处理后就不会在事件处理周期继续传播。

让我们看看现在的程序:

import os
import wx
ID_ABOUT=101
ID_EXIT=110
class MainWindow(wx.Frame):
def __init__(self,parent,id,title):
 wx.Frame.__init__(self,parent,wx.ID_ANY, title, size = (200,100))
 self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
 self.CreateStatusBar() # A StatusBar in the bottom of the window
 # Setting up the menu.
 filemenu= wx.Menu()
 filemenu.Append(ID_ABOUT, "&About"," Information about this program")
 filemenu.AppendSeparator()
 filemenu.Append(ID_EXIT,"E&xit"," Terminate the program")
 # Creating the menubar.
 menuBar = wx.MenuBar()
 menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
 self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.
 wx.EVT_MENU(self, ID_ABOUT, self.OnAbout) # attach the menu-event ID_ABOUT to the
                                                    # method self.OnAbout
 wx.EVT_MENU(self, ID_EXIT, self.OnExit)   # attach the menu-event ID_EXIT to the
                                                    # method self.OnExit
 self.Show(True)
def OnAbout(self,e):
 d= wx.MessageDialog( self, " A sample editor \n"
                     " in wxPython","About Sample Editor", wx.OK)
                     # Create a message dialog box
 d.ShowModal() # Shows it
 d.Destroy() # finally destroy it when finished.
def OnExit(self,e):
 self.Close(True)  # Close the frame.
app = wx.PySimpleApp()
frame = MainWindow(None, -1, "Sample editor")
app.MainLoop()

更多有趣的东西

  • 如果一个文本编辑器不能保存用户的输入,不能打开一个已有的文档,那这个编辑器可以算一个废品。下面我们加上打开已有文档的代码,通过一个系统的文件浏览对话框打开文件:
        def OnOpen(self,e):
       """ Open a file"""
       self.dirname = ''
       dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", wx.OPEN)
       if dlg.ShowModal() == wx.ID_OK:
           self.filename=dlg.GetFilename()
           self.dirname=dlg.GetDirectory()
           f=open(os.path.join(self.dirname,self.filename),'r')
           self.control.SetValue(f.read())
           f.close()
       dlg.Destroy()
    
    • 上面的代码其实只有简单的三个步骤:
      • 首先,创建一个系统的文件浏览对话框
      • 然后,调用ShowModal方法,弹出一个模态对话框,等待用户按下OK按钮或者Cancel按钮。

      • 最后,得到用户所选择的文件夹和文件名,调用destroy方法然后销毁这个窗口
      这里没有给出怎么添加一个打开菜单并将它的事件连接到onOpen方法的代码,相信你看过上面的例子应该已经可以自己完成了。

    可能的扩展

    我们的编辑器还远远不能算是一个专业的编辑器,还有更多的技术可以用到这个编辑器上让它更专业,诸如:
    • 拖拽操作.
    • MDI (多窗口窗体)
    • Tab view/multiple files (通过标签视图显示更多文件)
    • Find/Replace dialog (查找,替换功能)
    • Print dialog (打印功能)

    • Macro-commands in python ( 在编辑器里面编写Python代码并运行)
    • etc ...

wxPython学习笔记(—) Hello World

0 评论  

第一个wxPython程序: "Hello, World" Hello World不知道是谁发明的,不过它已经成为所有程序教程的典范了,呵呵,几乎所有的Hello World都尽量做到简洁明了,wxPython也不例外,试看如下代码:

import wx
app = wx.PySimpleApp()
frame = wx.Frame(None, wx.ID_ANY, "Hello World")
frame.Show(True)
app.MainLoop()
  • 下面就是在Windows上运行的结果:
  • 代码很短很强大,首先导入wx 模块,然后初始化一个wx.PySimpleApp对象,接下来是窗口对象wx.Frame,一个有标题栏,最小最大关闭按钮的窗口就创建好了[4],调用show方法让这个窗口显示出来。最后一句MainLoop作用则是使整个程序进入事件循环,学过Swing的可能会觉得这句话似乎有点多余,个人感觉可能是由于与平台底层GUI控件的兼容,诸如MFC之类的GUI的事件其实就是一个无限循环,无限的去循环检查有没有新的事件产生,并调用相应的处理函数。回到wx.Frame创建这里,这应该是这几句Code中看起来稍微复杂的一句了:

          wx.Frame(Parent, Id, "Hello World")
  • wxPython里面的大多数控件在构造函数里面都有类似的参数构成:一个Parent 对象作为第一个参数,然后是控件的Id作为第二个参数,就像你所看到的,可以使用None或者wx.ID_ANY来做默认值(表示这个Frame对象没有父对象,只需要一个系统自定义的Id)

[4]这里我们创建的是一个简单的窗口,也可能是一个MDI的窗口。 后话:这个窗口是wxPython自动生成的,大小,窗体位置,窗口背景什么都是它自己决定的。 可以通过下面代码指定大小,窗体位置,窗口背景 frame.Size = (300,200)#窗体大小 frame.BackgroundColour = (200,120,130) #窗体背景颜色,随便写的一个RGB颜色 frame.SetPosition((200,100))#窗体位置,x,200, y 100
Reference:wxPython Getting Start

【转】Python程序打包成安装包

0 评论  

The McMillan Installer

The mcillian installer development is discontinued.

mirror: http://davidf.sjsoft.com/mirrors/mcmillan-inc/installer_dnld.html

Continued development(not tested yet): http://pyinstaller.hpcf.upr.edu/cgi-bin/trac.cgi

This works on Win32. Unzip the Installer in a directory of your choice, and cd there.

Configure the Installer by running:

python Configure.py

Python must be in your PATH for this to work, if it's not, type from the command prompt:

PATH=%PATH%;c:\python23

where c:\python23 must be replaced with the root of your python installation. Then, assuming the source code is app.py (placed in c:\source):

python Makespec.py --upx --onefile --noconsole c:\source\app.py
python Build.py  app\app.spec

Replace 'app' everywhere above with your application name.

You will end up with app\app.exe under the Installer dir.This is a one file .exe containing all the application. If you don't want a one-file build, suppress the option --onefile above. If you don't have upx installed (or don't want to use it), suppress the option --upx above. The option --noconsole is needed to produce a windows gui application, instead of a console one (so the command shell won't pop up when you run the application).

[ More details to be written... ]

py2exe

http://py2exe.sourceforge.net/

Create a setup.py script for using py2exe to generating the exe file. (The script to compile in this case is wxTail.py):

# setup.py
from distutils.core import setup
import py2exe
setup(name="wxTail",scripts=["wxTail.py"],)

Sample of the win32 command for running py2exe:

python setup.py py2exe

If you use the unicode version of wxpython you have to manually include the file unicows.dll form your python installation directory. Otherwise the application will crash at least on Windows 98.

--GeraldKlix

[ More details to be written... ]

Installer

To turn your binary and accompanying library files into a Windows installer you can use:

Issues

When using py2exe with pythoncom (or with wxPython's ActiveXWrapper which uses pythoncom) py2exe has trouble finding the code for the generated COM wrapper modules and you end up with import errors. Here is the solution, which was sent to the mail list by Clark C. Evans:

  • When pythonwin is called to create an Python binding for a COM component, it generates a new python class and puts this class in the gen_py directory (which magically appears). I believe the problem is that the py2exe program doesn't expand the Python path to include the deployment directory, otherwise this directory would be found... To work-aroud this problem, simply use the makepy program to generate a python wrapper for the activeX component you have (for example, IE Explorer). Then, rename this module file to something more palatable (like ie.py). Then, instead of using "ensure module" simply import the re-named file -- the imported module is the class module. For example, to make the IE ActiveX demo work...
    1. Generate ie.py using makepy using the "-o" option
    2. Replace the "ensure module" stuff in the demo code with...
          from wxPython.wx import *
         if wxPlatform == '__WXMSW__':
             from wxPython.lib.activexwrapper import MakeActiveXClass
             import ie5
             browserModule = ie5
    No other changes seem to be necessary.

Another work-around if you run into issues running py2exe compiled programs with the ActiveXWrapper controls (specifically the PDF Window control in wxPython 2.8) is to add a typelibs entry to the options argument in your setup.py file. See the sample setup.py below for an example.

from distutils.core import setup
import py2exe

manifest = """



myProgram

   
       
   


"""

"""
installs manifest and icon into the .exe
but icon is still needed as we open it
for the window icon (not just the .exe)
changelog and logo are included in dist
"""

setup(

   options = {'py2exe': {
                           'compressed': 1,
                           'optimize': 2,
                           'bundle_files': 3,
                           'typelibs' : [("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1)],
                       }
        },


   windows = [
       {
           "script": "myprogram.py",
           "icon_resources": [(1, "program.ico")],
           "other_resources": [(24,1,manifest)],
       }
   ],
     data_files=["help.txt",
                 "program.ico",
                 "program.ini"],

)

Basically the typelibs line ensures py2exe picks up the dynamically imported module in pdfwin.py that is included with the Windows wxPython distribution.

    _browserModule = win32com.client.gencache.EnsureModule(
       "{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1)

On Linux

Summary

A binary distribution of a Python/wxPython program on Linux has these advantages:

  • There is no need for the user to have Python, wxPython or any other extensions you use installed
  • The versions of Python, wxPython and extensions are the ones you ship, not any they may already have installed. That means you don't need to worry about users using different versions of the extensions with your software.

Prerequisites

cx_Freeze

cx_Freeze turns a Python script into a binary file and any referenced binary modules.

Download cx_Freeze from http://starship.python.net/crew/atuining/ I recommend getting the binary distribution. If you extract it in /opt, then it will end up installed in /opt/cx_Freeze-2.1/ (this location is assumed through the rest of this document).

Also note that while cx_Freeze is free software, you do need to abide by the license agreement on the same page.

chrpath

The wxPython shared libraries have some pathnames hardcoded into them (also known as an rpath). chrpath removes this hardcoded path for where other shared libraries are searched.

Download chrpath from http://freshmeat.net/projects/chrpath/ By default it installs in /usr/local/bin which should be on your path.

Making your binary distribution

Make an output directory

Create a clean directory for the resulting files. I make one named dist.

Run cxFreeze

Assuming the main entrypoint to your program is example.py, this is what you run:

$ cxpath=/opt/cx_Freeze-2.1
$ env PATH=$cxpath:$PATH FreezePython --install-dir=dist --base-binary=$cxpath/ConsoleSetLibPathBase example.py

Everything should end up in the dist subdirectory, and the main binary will be named dist/example

Run chrpath

You now need to remove hard coded path information from the wxPython and other shared libraries. I use this shell script:

for i in *.so
do
   if chrpath $i 2>/dev/null | grep = >/dev/null
   then
       echo "Fixing $i"
       chrpath -d $i
   fi
done

Change into the dist subdirectory and run the script. It should fix at least wxPython.wxc.so, and same other wx-controls you may use (eg calendar).

Package it up

You can now just tar up the dist subdirectory. Users can place the contents anywhere they choose on the filesystem, and call the main executable for everything to work.

I normally put all the files in a subdirectory of /usr/lib (for example: /usr/lib/example-1.0 and then put a wrapper script in /usr/bin that execs the binary in /usr/lib/example-1.0.

On Mac

py2app

http://undefined.org/python/py2app.html

BundleBuilder.py

The Python included with Mac OS X contains a tool called BundleBuilder.py which lets you package Python scripts into ".app" bundles that can be distributed on computers even without Python installed. (Although OS X 10.3 contains a complete implementation of Python.) Documentation on this tool (including an example of a wxPython app building script) can be found here:

http://www.python.org/cgi-bin/moinmoin/BundleBuilder

The important part to note is that you must manually include the wxWindows dynamic libraries at this point. See the lines in the example script containing myapp.libs.append to see how to do so. Hopefully a more targeted and detailed tutorial will be forthcoming. =) In the meantime, please feel free to post your questions to either wxPython-mac@lists.sourceforge.net or pythonmac-sig@python.org .

Examples

BitPim

The bitpim project produces Windows and Linux binary installers that don't require the user to have Python or wxPython installed (or even have to know what they are!)

Code is available in http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/bitpim/bitpim/

makedist.py does the actual build an invokes the various other tools. bitpim.iss is the innosetup file. p2econfig.py is the py2exe file.

原文地址 http://wiki.wxpython.org/index.cgi/CreatingStandaloneExecutables

【转】linux下配置,启动多个tomcat

0 评论  

1. 环境:

  • Red Hat Linux 9(本人CentOs5.2,其实想想这个问题跟Linux的版本的关系的可以忽略)
  • Tomcat 5.5.17(Tomcat5.5.27)

2. 需要解决一下几个问题

  • 不同的tomcat启动和关闭监听不同的端口
  • 不同的tomcat的启动文件startup.sh 中要指定各自的CATALINA_HOME和CATALINA_BASE这两个环境变量。

3. 解决步骤:

3.1. 修改/etc目录下的profile文件,添加一组java环境变量,和两组CATALINA环境变量;修改后的profile文件示例如下:

JAVA_HOME=/usr/java/jdk

CLASSPATH=$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib:$JAVA_HOME/bin

export JAVA_HOME CLASSPATH

CATALINA_BASE=/usr/local/tomcat

CATALINA_HOME=/usr/local/tomcat

export CATALINA_BASE CATALINA_HOME

CATALINA_2_BASE=/usr/local/tomcat2/apache-tomcat-5.5.17

CATALINA_2_HOME=/usr/local/tomcat2/apache-tomcat-5.5.17

export CATALINA_2_BASE CATALINA_2_HOME

TOMCAT_HOME=/usr/local/tomcat

export TOMCAT_HOME

TOMCAT_2_HOME=/usr/local/tomcat2/apache-tomcat-5.5.17

export TOMCAT_2_HOME

3.2. 第一个安装在/usr/local/tomcat处的tomcat,保持解压后的原状不用修改。修改第二个安装在/usr/local/tomcat2/apache-tomcat-5.5.17处的tomcat。需要修改两个地方:

3.2.1. 修改server.xml配置和第一个不同的启动、关闭监听端口。修改后示例如下:

  端口:8005->9005

 端口:8080->9080

maxThreads="150" minSpareThreads="25" maxSpareThreads="75"

enableLookups="false" redirectPort="8443" acceptCount="100"

connectionTimeout="20000" disableUploadTimeout="true" />

端口:8009->9009

enableLookups="false" redirectPort="8443" protocol="AJP/1.3" />

3.2.2. 修改bin下的startup.sh和shutdown.sh。修改后的示例如下:(同样的修改)

export JAVA_HOME=/usr/jdk(如未设置过Java_home)

export PATH=$PATH:$JAVA_HOME/bin(同上)

export CLASSPATH=$JAVA_HOME/lib(同上,这些设置最好放到profile里面去)

export CATALINA_HOME=$CATALINA_2_HOME 利用profile中第二组设置

export CATALINA_BASE=$CATALINA_2_BASE 利用profile中第二组设置

4. 修改完毕后,必须重新启动linux。可能是因为修改了profile文件的缘故?

5. 分别进入两个tomcat的bin目录,启动tomcat——./startup.sh

6. 然后访问http://localhost:8080 和 http://localhost:9080 都可以看到熟悉的tomcat欢迎界面。

7. 如果想启动多个可以依此法类推…… 转自:http://blog.csdn.net/guorui303/archive/2007/02/08/1505442.aspx

【转】Apache + Tomcat*2集群 负载平衡(Linux环境) 一台机器上实测

0 评论  

说明:一台apache主机,两台tomcat主机

(注:做Research,没那么多主机,只有一台,跑了apache进程一个,Tomcat进程两个,这里还涉及到一个问题,在同一个机器上跑两个Tomcat,Windows里面是很简单的,改conf文件夹下面的server.xml里面的端口,不冲突就可以了,Linux里面却没这么简单,参考另一篇转的文章,如何在Linux里面开两个Tomcat,另所有步骤均通过Putty远程连接到Linux环境进行)

步骤如下:

  1. 安装JDK、
  2. 安装Apache、
  3. 安装Tomcat、
  4. 配置Apache代理、
  5. 配置Tomcat集群

一、安装JDK(所有运行Tomcat主机,即web服务器) 1.下载JDK的bin包,如jdk-1_5_0_02-linux-i586.rpm.bin ,给其添加执行权限(注:chmod 777 jdk-1_5_0_02-linux-i586.rpm.bin ),执行#./jdk-1_5_0_02-linux-i586.rpm.bin , 在

当前目录生成rpm安装包,同样给其添加执行权限。 再执行 #rpm -ivh jdk-1_5_0_02-linux-i586.rpm 出现安装协议 按接受即可。 2.设置环境变量 #vi /etc/profile 在其最后加入

JAVA_HOME =/ usr / java / jdk1. 5 .0_02 CLASSPATH = .:$JAVA_HOME / lib:$JAVA_HOME / jre / lib PATH = $PATH:$JAVA_HOME / bin:$JAVA_HOME / jre / bin export JAVA_HOME CLASSPATH PATH

保存退出

(注:如需验证是否设置正确,可以运行 echo $JAVA_HOME的方式来查看环境变量是否正确,不过运行之前需要运行 source /etc/profile更新环境变量) 3.要使JDK在所有的用户中使用,可以这样:vi /etc/profile.d/java.sh在新的java.sh中输入以下内容: #set java environment JAVA_HOME=/usr/java/jdk1.5.0_02 CLASSPATH=.:$JAVA_HOME/lib:$JAVA_HOME/jre/lib PATH=$PATH:$JAVA_HOME/bin:$JAVA_HOME/jre/bin export JAVA_HOME CLASSPATH PATH 保存退出,然后给java.sh分配权限:chmod 755 /etc/profile.d/java.sh

二、安装Apache(访问代理主机) 1.下载apache源代码 wget http://archive.apache.org/dist/httpd/httpd-2.2.2.tar.gz

解压缩 tar fvxz httpd-2.2.2.tar.gz

2.进入解压后的目录。进行配置:

./configure --prefix=/usr/local/apache --enable-module=most --enable-proxy --enable-proxy-ajp --enable-forward --enable-proxy-connect --enable-proxy-http --enable-so --enable-deflate --enable-headers --enable-include (拷贝到该目录下执行即可)

上面的配置,用到了其他一些模块,说不定以后会用到,如支持ssi的include模块。

3.编译(编译如果不成功,确认一下你的linux是否安装有编译所需要的c环境和其他需要的类库) make

4.安装 make install

5.进入/usr/local/apache目录,运行apache ./apachectl -k start

运行apache后,浏览一下是否运行正常。

关闭apache ./apachectl -k stop

6.把apache作为linux的启动就运行服务程序(该步骤未尝试) 执行如下操作:cp /usr/apache/bin/apachectl /etc/rc.d/init.d/httpd 确认linux以前安装的httpd(apache)不需要了,你可覆盖掉以前apache的httpd文件。 chkconfig --add httpd 运行linux的setup,把httpd服务默认设定为自动运行。 到现在,你就可用另一种方式来启动、关闭apache了。如service httpd start

三、安装tomcat(Web服务器) 1.下载jakarta-tomcat-5.5.20.tar.gz tar zxf jakarta-tomcat-5.5.20.tar.gz 解压文件 (如解压到/usr/local/) 2.设置环境变量 #vi /etc/profile 添加 CATALINA_HOME=/usr/local/jakarta-tomcat-5.5.30 export CATALINA_HOME

(注:如只有一台主机,见如何在Linux里面同时开两个Tomcat) 保存退出

3.修改JVM内存:/bin/catalina.sh 文件 在下# ----- Execute The Requested Command ----------------- # Bugzilla 37848: only output this if we have a TTY if [ $have_tty -eq 1 ]; then echo "Using CATALINA_BASE: $CATALINA_BASE" echo "Using CATALINA_HOME: $CATALINA_HOME" echo "Using CATALINA_TMPDIR: $CATALINA_TMPDIR" if [ "$1" = "debug" -o "$1" = "javac" ] ; then echo "Using JAVA_HOME: $JAVA_HOME" else echo "Using JRE_HOME: $JRE_HOME" fi fi 添加以下内容:

CATALINA_OPTS = " $CATALINA_OPTS -Xms256m -Xmx512m -XX:PermSize=32m -XX:MaxPermSize=128m $JPDA_OPTS " JAVA_OPTS = " $JAVA_OPTS -Djava.awt.headless=true " echo " Using CATALINA_OPTS: $CATALINA_OPTS " echo " Using JAVA_OPTS: $JAVA_OPTS "

4.运行/usr/local/jakarta-tomcat-5.5.30/bin/startup.sh 启动tomcat服务器 测试是否正常

四、配置apache代理(适用mod_proxy_ajp.so) 编辑apache配置文件 #vi /usr/apache/conf/httpd.conf 1.配置proxy_ajp #加载解析模块(windows下,或linux采用动态加载模式下需配置。前面我们的linux编译时把下面的模块嵌入到了apache中

,所以不用再加载) LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_ajp_module modules/mod_proxy_ajp.so 2.配置文件添加

ProxyPass / balancer://tomcatcluster/ stickysession=JSESSIONID nofailover=on timeout=5 maxattempts=3 ProxyPassReverse / balancer://tomcatcluster/ BalancerMember ajp://192.168.18.152:8019 smax=2 loadfactor=1 route=tomcat2 BalancerMember ajp://192.168.18.152:8009 smax=2 loadfactor=2 route=tomcat1

以上说明请参见mod_proxy中文手册 http://www.6bee.com/tech/ApacheMenu/mod/mod_proxy.html 3.其他说明

1、apache对tomcat的支持历史:apache第2.1版本后,内置了proxy_ajp,而jk2已经没人开发了,jk则支持到apache的

2.0.58版本。 proxy_ajp配置较简单,但可配置性还不如jk2,主要表现在proxy_ajp目前只支持配置到目录,还不支持对文件名称的pattern模式匹

配(即还不能定义到只对jsp文件起作用)。

2、因为proxy_ajp的配置,还不支持对文件名称的pattern模式匹配,所以你要特别注意: ——尽量把jsp和静态文件和图片路径分不同的目录来管理; ——对于静态文件和图片路径,如/images,你可用“ProxyPass /images !”来禁止ProxyPass,从而来让apache来直接处理图片的请

求。 ——关于apache的ssi(即shtml,include)与tomcat的集成时,shtml文件不能处于ProxyPass的控制下(即不能在ProxyPass目录)

,而shtml调用的jsp须在ProxyPass有效控制下;

五、配置Tomcat负载均衡、集群 1.修改tomcat 的 conf/server.xml 的 去掉注释 jvmRoute是tomcat路由标示,由此区分两台tomcat主机,那么第二台就改为 jvmRoute="tomcat2"> 加上注释 2.修改tomcat 的 conf/server.xml 的 去掉注释

3.修改tomcat 的 conf/server.xml 的

把上面的注释拿掉 就ok 了!

(因为是同一台机器上运行两个,所以另外一个Tomcat除了需要改8080,8005,8009端口之外还需要改这里的集群监听端口4001)

4.在每个webapps应用中,修改web.xml文件 添加元素 最后完工,重启tomcat,apahce测试平衡负载,新建jsp页面 <% Runtime lRuntime = Runtime.getRuntime(); out.println("*** BEGIN MEMORY STATISTICS *** "); out.println("Free Memory: "+lRuntime.freeMemory()/1024/1024+"M "); out.println("Max Memory: "+lRuntime.maxMemory()/1024/1024+"M "); out.println("Total Memory: "+lRuntime.totalMemory()/1024/1024+"M "); out.println("Available Processors : "+lRuntime.availableProcessors()+" "); out.println("*** END MEMORY STATISTICS ***"); %> <%= request.getSession().getId() %> 放入到两台tomcat的ROOT目录中测试 转自:http://envoydada.javaeye.com/blog/95162