applicationContext-zookeeper.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd"> <description>zookeeper 放入spring容器,项目启动加载的时候就建立和zk的连接</description> <!-- 创建重连策略 --> <bean id="retryPolicy" class="org.apache.curator.retry.ExponentialBackoffRetry"> <!-- 每次重试连接的等待时间 --> <constructor-arg index="0" value="1000"></constructor-arg> <!-- 设置的重连的次数 --> <constructor-arg index="1" value="5"></constructor-arg> </bean> <!-- 创建zookeeper客户端 --> <bean id="client" class="org.apache.curator.framework.CuratorFrameworkFactory" factory-method="newClient" init-method="start"> <constructor-arg index="0" value="192.168.147.142:2181"></constructor-arg> <constructor-arg index="1" value="10000"></constructor-arg> <constructor-arg index="2" value="10000"></constructor-arg> <constructor-arg index="3" ref="retryPolicy"></constructor-arg> </bean> <!-- 客户端配置 --> <!-- init-method="init" 不使用zk的话,仅仅只是测试为了方便可以把这个方法暂时拿掉 --> <bean id="ZKCurator" class="com.javaxl.web.util.ZKCurator" init-method="init"> <constructor-arg index="0" ref="client"></constructor-arg> </bean> </beans>
ZKCurator.java
package com.javaxl.web.util; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs.Ids; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZKCurator { // zk客户端 private CuratorFramework client = null; final static Logger log = LoggerFactory.getLogger(ZKCurator.class); public ZKCurator(CuratorFramework client) { this.client = client; } public void init() { client = client.usingNamespace("admin"); try { // 判断在admin命名空间下是否有bgm节点 /admin/bmg if (client.checkExists().forPath("/bgm") == null) { /** * 对于zk来讲,有两种类型的节点: * 持久节点: 当你创建一个节点的时候,这个节点就永远存在,除非你手动删除 * 临时节点: 你创建一个节点之后,会话断开,会自动删除,当然也可以手动删除 */ client.create().creatingParentsIfNeeded() .withMode(CreateMode.PERSISTENT) // 节点类型:持久节点 .withACL(Ids.OPEN_ACL_UNSAFE) // acl:匿名权限 .forPath("/bgm"); log.info("zookeeper初始化成功..."); log.info("zookeeper服务器状态:{}", client.isStarted()); } } catch (Exception e) { log.error("zookeeper客户端连接、初始化错误..."); e.printStackTrace(); } } /** * @Description: 增加或者删除bgm,向zk-server创建子节点,供小程序后端监听 */ public void sendBgmOperator(String bgmId, String operObj) { try { client.create().creatingParentsIfNeeded() .withMode(CreateMode.PERSISTENT) // 节点类型:持久节点 .withACL(Ids.OPEN_ACL_UNSAFE) // acl:匿名权限 .forPath("/bgm/" + bgmId, operObj.getBytes()); } catch (Exception e) { e.printStackTrace(); } } }
用外置tomcat启动碰到下列错误
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
解决方案:
其实是你的jar文件没有同步发布到自己项目的lib目录中
(如果是用Maven进行构建的话) 可以试试 下面的办法
–rebuild下project就可以了
项目点击右键 点击 Properties 选择Deployment Assembly 再点击右边的Add按钮 选择
Java Build Path Entries后点击Next按钮 然后选择你的Maven Dependencies 确定即可
将上篇博客的配置文件的形式改成配置类的形式
resource.properties
com.javaxl.zookeeperServer=192.168.147.142:2181 #commonFooterJS.jsp com.javaxl.bgmServer=http://192.168.100.5.37/mvc com.javaxl.fileSpace=C:\\javaxl_videos_dev
ResourceConfig.java
package com.javaxl.cofig; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @ConfigurationProperties(prefix="com.javaxl") @PropertySource("classpath:resource.properties") public class ResourceConfig { private String zookeeperServer; private String bgmServer; private String fileSpace; public String getZookeeperServer() { return zookeeperServer; } public void setZookeeperServer(String zookeeperServer) { this.zookeeperServer = zookeeperServer; } public String getBgmServer() { return bgmServer; } public void setBgmServer(String bgmServer) { this.bgmServer = bgmServer; } public String getFileSpace() { return fileSpace; } public void setFileSpace(String fileSpace) { this.fileSpace = fileSpace; } }
ZKCuratorClient.java
package com.javaxl; import java.io.File; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.javaxl.cofig.ResourceConfig; import com.javaxl.enums.BGMOperatorTypeEnum; import com.javaxl.utils.JsonUtils; @Component public class ZKCuratorClient { // zk客户端 private CuratorFramework client = null; final static Logger log = LoggerFactory.getLogger(ZKCuratorClient.class); // @Autowired // private BgmService bgmService; // public static final String ZOOKEEPER_SERVER = "192.168.1.210:2181"; @Autowired private ResourceConfig resourceConfig; public void init() { if (client != null) { return; } // 重试策略 RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5); // 创建zk客户端 client = CuratorFrameworkFactory.builder().connectString(resourceConfig.getZookeeperServer()) .sessionTimeoutMs(10000).retryPolicy(retryPolicy).namespace("admin").build(); // 启动客户端 client.start(); try { // String testNodeData = new String(client.getData().forPath("/bgm/18052674D26HH3X4")); // log.info("测试的节点数据为: {}", testNodeData); addChildWatch("/bgm"); } catch (Exception e) { e.printStackTrace(); } } public void addChildWatch(String nodePath) throws Exception { final PathChildrenCache cache = new PathChildrenCache(client, nodePath, true); cache.start(); cache.getListenable().addListener(new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED)) { log.info("监听到事件 CHILD_ADDED"); // 1. 从数据库查询bgm对象,获取路径path String path = event.getData().getPath(); String operatorObjStr = new String(event.getData().getData()); Map<String, String> map = JsonUtils.jsonToPojo(operatorObjStr, Map.class); String operatorType = map.get("operType"); String songPath = map.get("path"); // String arr[] = path.split("/"); // String bgmId = arr[arr.length - 1]; // Bgm bgm = bgmService.queryBgmById(bgmId); // if (bgm == null) { // return; // } // 1.1 bgm所在的相对路径 // String songPath = bgm.getPath(); // 2. 定义保存到本地的bgm路径 // String filePath = "C:\\javaxl_videos_dev" + songPath; String filePath = resourceConfig.getFileSpace() + songPath; // 3. 定义下载的路径(播放url) String arrPath[] = songPath.split("\\\\"); String finalPath = ""; // 3.1 处理url的斜杠以及编码 for(int i = 0; i < arrPath.length ; i ++) { if (StringUtils.isNotBlank(arrPath[i])) { finalPath += "/"; finalPath += URLEncoder.encode(arrPath[i], "UTF-8") ; } } // String bgmUrl = "http://192.168.1.2:8080/mvc" + finalPath; String bgmUrl = resourceConfig.getBgmServer() + finalPath; if (operatorType.equals(BGMOperatorTypeEnum.ADD.type)) { // 下载bgm到spingboot服务器 URL url = new URL(bgmUrl); File file = new File(filePath); FileUtils.copyURLToFile(url, file); client.delete().forPath(path); } else if (operatorType.equals(BGMOperatorTypeEnum.DELETE.type)) { File file = new File(filePath); FileUtils.forceDelete(file); client.delete().forPath(path); } } } }); } }
WebMvcConfig.java
package com.javaxl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.javaxl.controller.interceptor.MiniInterceptor; @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 可以让http://192.168.43.37:8081/login这样的url被微信端调用 registry.addResourceHandler("/**") // http://192.168.43.37:8081/swagger-ui.html依然能够被访问 .addResourceLocations("classpath:/META-INF/resources/") // 添加file:C:/javaxl_videos_dev/与http://192.168.43.37:8081/的虚拟文件映射 .addResourceLocations("file:C:/javaxl_videos_dev/"); } @Bean public MiniInterceptor miniInterceptor() { return new MiniInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(miniInterceptor()).addPathPatterns("/user/**") .addPathPatterns("/video/upload", "/video/uploadCover", "/video/userLike", "/video/userUnLike", "/video/saveComment") .addPathPatterns("/bgm/**") .excludePathPatterns("/user/queryPublisher"); super.addInterceptors(registry); } @Bean(initMethod="init") public ZKCuratorClient zkCuratorClient() { return new ZKCuratorClient(); } }
over......
备案号:湘ICP备19000029号
Copyright © 2018-2019 javaxl晓码阁 版权所有