Nginx+Tomcat在Windows下做负载均衡

本文介绍了一种在Windows环境下使用Nginx对Tomcat服务器进行负载均衡的方法。通过配置两个Tomcat实例,并调整Nginx的设置以实现流量的合理分配,解决了高并发访问带来的问题。

一、 为什么需要对 Tomcat 服务器做负载均衡:

Tomcat 服务器作为一个 Web 服务器,其并发数在 300-500 之间,如果有超过 500 的并发数便会出现 Tomcat 不能响应新的请求的情况,严重影响网站的运行。另外,在访问量大的情况下, Tomcat 的线程数会不断增加。由于 Tomcat 自身对内存的占用有控制,当对内存的占用达到最大值时便会出现内存溢出,对网站的访问严重超时等现象,这时便需要重新启动 Tomcat 以释放占用的内存,这样做便会阻断网站运行。

所以对 Tomcat 做负载均衡便很有必要。目前可以和 Tomcat 做负载均衡的主流服务器是 Apache ,但是 Nginx 由于功能多、配置简单等优点逐渐成为很多负载均衡服务器的首选。 Nginx 的并发数可达到 50000 ,所以理论上可以和 Tomcat  1:100 的比例来配置,这样便可以很好的解决网站并发瓶颈问题。

二、 Nginx+Tomcat  Windows 下负载均衡配置方法:

Nginx+Tomcat  Windows 下做负载均衡相对在 Linux 下简单不少,因为不论是 Nginx 还是 Tomcat 只需要下载 Windows 下的安装包解压到某个目录下,然后就可以做配置了。

               我选择的 Nginx  nginx-0.8.49 这个版本, Tomcat 选择的是 apache-tomcat-6.0.26 

         下面就是配置过程 :

         1.  nginx-0.8.49.rar 压缩包直接解压到某个目录下 (  D:/ 负载均衡 /nginx) 

       2.  apache-tomcat-6.0.26.rar 压缩包解压,因为是做负载均衡,所以至少要解压两个。 ( 如分别解压到 D:/ 负载均衡 /tomcat_1  D:/ 负载均衡 /tomcat_2 下面 ) 

         3. 将要发布的项目发布到两个 Tomcat 根目录下的 webapps 下,保证两个 Tomcat 下面的项目名称相同。

         4. 修改其中一个 Tomcat 的配置文件,该配置文件位于 Tomcat 目录下的 /conf/ 下,文件名为 server.xml ,修改其中的 <Server port="8005" shutdown="SHUTDOWN">  <Server port="8006" shutdown="SHUTDOWN"> ,修改其中的

<Connector port="8080" protocol="HTTP/1.1"

               connectionTimeout="20000"

               redirectPort="8443" />

<Connector port="8088" protocol="HTTP/1.1"

               connectionTimeout="20000"

               redirectPort="8443" />

修改后的文件如下:

 

<?xml version='1.0' encoding='utf-8'?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- Note: A "Server" is not itself a "Container", so you may not define subcomponents such as "Valves" at this level. Documentation at /docs/config/server.html --> <Server port="8006" shutdown="SHUTDOWN"> <!--APR library loader. Documentation at /docs/apr.html --> <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" /> <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html --> <Listener className="org.apache.catalina.core.JasperListener" /> <!-- Prevent memory leaks due to use of particular java/javax APIs--> <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" /> <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html --> <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" /> <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> <!-- Global JNDI resources Documentation at /docs/jndi-resources-howto.html --> <GlobalNamingResources> <!-- Editable user database that can also be used by UserDatabaseRealm to authenticate users --> <Resource name="UserDatabase" auth="Container" type="org.apache.catalina.UserDatabase" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" pathname="conf/tomcat-users.xml" /> </GlobalNamingResources> <!-- A "Service" is a collection of one or more "Connectors" that share a single "Container" Note: A "Service" is not itself a "Container", so you may not define subcomponents such as "Valves" at this level. Documentation at /docs/config/service.html --> <Service name="Catalina"> <!--The connectors can use a shared executor, you can define one or more named thread pools--> <!-- <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="150" minSpareThreads="4"/> --> <!-- A "Connector" represents an endpoint by which requests are received and responses are returned. Documentation at : Java HTTP Connector: /docs/config/http.html (blocking & non-blocking) Java AJP Connector: /docs/config/ajp.html APR (HTTP/AJP) Connector: /docs/apr.html Define a non-SSL HTTP/1.1 Connector on port 8080 --> <Connector port="8088" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> <!-- A "Connector" using the shared thread pool--> <!-- <Connector executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> --> <!-- Define a SSL HTTP/1.1 Connector on port 8443 This connector uses the JSSE configuration, when using APR, the connector should be using the OpenSSL style configuration described in the APR documentation --> <!-- <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" /> --> <!-- Define an AJP 1.3 Connector on port 8009 --> <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" /> <!-- An Engine represents the entry point (within Catalina) that processes every request. The Engine implementation for Tomcat stand alone analyzes the HTTP headers included with the request, and passes them on to the appropriate Host (virtual host). Documentation at /docs/config/engine.html --> <!-- You should set jvmRoute to support load-balancing via AJP ie : <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1"> --> <Engine name="Catalina" defaultHost="localhost"> <!--For clustering, please take a look at documentation at: /docs/cluster-howto.html (simple how to) /docs/config/cluster.html (reference documentation) --> <!-- <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> --> <!-- The request dumper valve dumps useful debugging information about the request and response data received and sent by Tomcat. Documentation at: /docs/config/valve.html --> <!-- <Valve className="org.apache.catalina.valves.RequestDumperValve"/> --> <!-- This Realm uses the UserDatabase configured in the global JNDI resources under the key "UserDatabase". Any edits that are performed against this UserDatabase are immediately available for use by the Realm. --> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/> <!-- Define the default virtual host Note: XML Schema validation will not work with Xerces 2.2. --> <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false"> <!-- SingleSignOn valve, share authentication between web applications Documentation at: /docs/config/valve.html --> <!-- <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> --> <!-- Access log processes all example. Documentation at: /docs/config/valve.html --> <!-- <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/> --> </Host> </Engine> </Service> </Server>

 

 

 

5. 修改 Nginx 配置文件 nginx.conf ,该文件位于 Nginx 根目录下的 /conf 下面。

  #gzip  on; 后面加入下面配置 :

upstream backend {

                   server localhost:8080;

                   server localhost:8088;

                   ip_hash;

         }

         其中 server localhost:8080 为第一个 Tomcat 的启动地址, server localhost:8088 为第二个 Tomcat 的启动地址, ip_hash 用于做 session 同步。

 修改第一个 server{} 配置中的 listen  80; 改为新的端口号,因为我的本机 80 端口被 IIS 占用,因此将此处改为 listen 800; 。并将

location / {

            root   html;

            index  index.html index.htm;

        }

改为:

location / {

            root   html;

            index  index.html index.htm;

                            proxy_pass                  http://backend; 

           proxy_redirect              off;

           proxy_set_header            Host $host;

           proxy_set_header            X-Real-IP $remote_addr;

           proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;

           client_max_body_size        10m;

           client_body_buffer_size     128k;

           proxy_connect_timeout       90;

           proxy_send_timeout          90;

           proxy_read_timeout          90;

           proxy_buffer_size           4k;

           proxy_buffers               4 32k;

           proxy_busy_buffers_size     64k;

           proxy_temp_file_write_size  64k;

        }

其中 proxy_pass 参数和 upstream backend{} 对应。

         经过上面这些步骤,负载均衡配置就完成,下面前分别启动两台 tomcat ,然后双击 nginx 根目录下的 nginx.exe 文件或者用 start nginx 启动 nginx ,打开浏览器,输入地址 :http://localhost:800 便可看到下面画面 :

这说明已经成功跳转到 Tomcat 上面。下面以来电秀具体项目为例,输入地址: http://localhost:800/ldxwebpersonal/personal/index/index.action 便可看到下面来电秀首页画面 :

我们再看看两个 Tomcat 下面的日志显示 :

端口号为 8080 的显示 :

端口号为 8088 的显示 :

这说明两个 tomcat 已经实现负载均衡。

Python 中集成 Ollama 可以通过使用 `ollama` 官方提供的 Python 客户端库来实现。Ollama 是一个本地运行的大型语言模型(LLM)工具,它支持多种模型,如 Llama 2、Mistral 等,并且可以通过简单的 APIPython 应用程序集成。 ### 安装 Ollama Python 库 首先,需要确保你已经在本地系统上安装了 Ollama。你可以从 [Ollama 官方网站](https://ollama.com/)下载并安装适用于你操作系统的版本。 接下来,安装 Python 客户端库。Ollama 提供了一个官方的 Python 包,可以通过 `pip` 安装: ```bash pip install ollama ``` ### 使用 Ollama Python 库 安装完成后,可以使用 `ollama` 模块来调用 OllamaAPI。以下是一个简单的示例,展示如何使用 Ollama 的 `generate` 方法来生成文本: ```python import ollama # 生成文本 response = ollama.generate(model='llama3', prompt='为什么天空是蓝色的?') # 打印响应 print(response['response']) ``` 在这个例子中,`model` 参数指定了要使用的模型(例如 `llama3`),`prompt` 参数是用户输入的提示词。Ollama 会根据提示词生成相应的文本,并返回一个包含 `response` 字段的字典。 ### 获取模型列表 如果你想查看当前可用的模型,可以使用以下代码: ```python import ollama # 获取模型列表 models = ollama.list() # 打印模型列表 for model in models['models']: print(model['name']) ``` ### 模型对话(Chat) Ollama 还支持更复杂的对话模式,允许你在多轮对话中保持上下文。以下是一个使用 `chat` 方法的示例: ```python import ollama # 开始对话 response = ollama.chat( model='llama3', messages=[ {'role': 'user', 'content': '你好,你能帮我做什么?'}, {'role': 'assistant', 'content': '你好!我可以帮助你回答问题、提供建议,甚至进行简单的创作。有什么我可以帮你的吗?'}, {'role': 'user', 'content': '你能告诉我关于机器学习的基础知识吗?'} ] ) # 打印响应 print(response['message']['content']) ``` 在这个例子中,`messages` 参数是一个包含多个对话记录的列表,每个记录都有一个 `role` 和 `content` 字段。Ollama 会根据这些对话记录生成相应的回复。 ### 错误处理 在实际应用中,建议添加错误处理逻辑,以应对可能出现的网络问题或模型加载失败等情况: ```python import ollama try: response = ollama.generate(model='llama3', prompt='为什么天空是蓝色的?') print(response['response']) except Exception as e: print(f"发生错误: {e}") ``` ### 相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值