
暂无个人介绍
我的博客即将入驻“云栖社区”,诚邀技术同仁一同入驻。
Java中JVM虚拟机详解 Java GC的那些事(上)(博主还有很多文章都很经典) CMS垃圾收集器介绍
1.首先需要安装docker最新版,docker 目前自带swarm容器编排工具 2.选中一台机器作为master,执行命令sudo docker swarm init [options] 3,再需要加入集群的集群上执行此命令 4.可以使用sudo docker node ls此命令来查询节点数 5编写docker-compose.yaml文件,目前我使用的是version 3版本,version2和3有区别,具体看官网介绍 贴一份完整的docker-compose.yaml供大家参考 version: '3' services: zookeeper: image: zookeeper ports: - "2181:2181" - "2182:2182" volumes: - "/data/clickhouse/zk/data:/data" - "/data/clickhouse/zk/log:/datalog" deploy: placement: constraints: - node.hostname == SHA11DMPHAMP01 # networks: # - clickhouse clickhouse203: image: yandex/clickhouse-server container_name: clickhouse203 expose: - "9000" - "8123" user: root privileged: true deploy: placement: constraints: - node.hostname == SHA11DMPHDOP01 ports: - "111.250.128.203:9000:9000" - "111.250.128.203:8123:8123" volumes: - "/data/clickhouse/etc:/etc/clickhouse-server" - "/data/clickhouse/data:/var/lib/clickhouse" - "/data/clickhouse/log:/var/log/clickhouse-server" ulimits: nofile: soft: 262144 hard: 262144 depends_on: - "zookeeper" # networks: # - clickhouse_network clickhouse204: image: yandex/clickhouse-server container_name: clickhouse204 expose: - "9000" - "8123" user: root privileged: true deploy: placement: constraints: - node.hostname == SHA11DMPHDOP02 ports: - "111.250.128.204:9001:9000" - "111.250.128.204:8124:8123" volumes: - "/data/clickhouse/etc:/etc/clickhouse-server" - "/data/clickhouse/data:/var/lib/clickhouse" - "/data/clickhouse/log:/var/log/clickhouse-server" ulimits: nofile: soft: 262144 hard: 262144 depends_on: - "zookeeper" # networks: # - clickhouse clickhouse205: image: yandex/clickhouse-server container_name: clickhouse205 expose: - "9000" - "8123" user: root privileged: true deploy: placement: constraints: - node.hostname == SHA11DMPHDOP03 ports: - "111.250.128.205:9002:9000" - "111.250.128.205:8125:8123" volumes: - "/data/clickhouse/etc:/etc/clickhouse-server" - "/data/clickhouse/data:/var/lib/clickhouse" - "/data/clickhouse/log:/var/log/clickhouse-server" ulimits: nofile: soft: 262144 hard: 262144 depends_on: - "zookeeper" # networks: # - clickhouse clickhouse206: image: yandex/clickhouse-server container_name: clickhouse206 expose: - "9000" - "8123" user: root privileged: true deploy: placement: constraints: - node.hostname == SHA11DMPHDOP04 ports: - "111.250.128.206:9003:9000" - "111.250.128.206:8126:8123" volumes: - "/data/clickhouse/etc:/etc/clickhouse-server" - "/data/clickhouse/data:/var/lib/clickhouse" - "/data/clickhouse/log:/var/log/clickhouse-server" ulimits: nofile: soft: 262144 hard: 262144 depends_on: - "zookeeper" # networks: # - clickhouse #networds: # clickhouse_network: docker-compose.yaml clickhouse的具体配置我就不介绍了,配置方面可以看我上一篇博客 希望大家尊重作者版权, 未经允许不得转载,违者必究!!
centos 安装clickhouse curl -s https://packagecloud.io/install/repositories/altinity/clickhouse/script.rpm.sh | sudo bash sudo yum list 'clickhouse*' sudo yum -y install clickhouse* docker安装可以直接克隆 https://gitee.com/pyzy/cloudcompute clickhouse 数据类型 数据类型没有boolean其他基本和hive一样,详细的看官网 clickhouse 数据类型 clickhouse 引擎 clickhouse有很多引擎,最常用的是 MergeTree家族 还有Distributed引擎 clickhouse 创建表 clickhouse可以创建本地表,分布式表,集群表 create table test()为本地表 CREATE TABLE image_label_all AS image_label ENGINE = Distributed(distable, monchickey, image_label, rand()) 分布式表 create table test on cluster()为集群表 贴一个完整的建表语句,使用ReplicatedMergeTree引擎 CREATE TABLE metro.metro_mdw_pcg ( storekey Int32, custkey Int32, cardholderkey Int32, pcg_main_cat_id Int32, pcg_main_cat_desc String, count Int32, quartly String ) ENGINE = ReplicatedMergeTree('/clickhouse/tables/metro/metro_mdw_pcg', '{replica}') PARTITION BY (quartly, pcg_main_cat_id) ORDER BY (storekey, custkey, cardholderkey) 保证数据复制 clickhouse数据操作 增加可以使用insert; 不能修改,也不能指定删除; 可以删除分区,会删除对应的数据 我使用--help看了一下有truncate table,但是没有具体使用过,如果要全部删除数据可以删除表,然后在建表查数据 可以使用脚本操作 database=$1 table=$2 echo "Truncate table "$2 create=`clickhouse-client --database=$1 --query="SHOW CREATE TABLE $table" | tr -d '\\'` clickhouse-client --database=$1 --query="DROP TABLE $table" clickhouse-client --database=$1 --query="$create" 再导入数据就可以了 导入数据,clickhouse支持很多文件类型 详细的看官方文档,文件导入导出 贴两个经常用的文件的导入 tsv,以"\t"隔开 clickhouse-client -h badd52c42f08 --input_format_allow_errors_num=1 --input_format_allow_errors_ratio=0.1 --query="INSERT INTO tablename FORMAT TSV"<file csv 以","或者"|"隔开 clickhouse-client -h adc3eaba589c --format_csv_delimiter="|" --query='INSERT INTO tablename FORMAT CSV' < file 数据查询 clickhouse的 查询sql 表单查询基本和标准sql一样,也支持limit 分页,但是inner join 的查询写法不一样,而且我用4亿+2000万inner join的速度很慢 两个sql对比 inner join要花费将近一分钟,使用in子查询仅3秒, 建议都使用in查询,clickhouse的单表查询速度很快,3亿数据count distinct 仅1秒左右 其它的技巧和知识,本人占时未做了解,希望大家能一起学习,一起进步
clickhouse时区设置 sudo vim /etc/clickhouse-server/config.xml <timezone>Asia/Shanghai</timezone> 保存,重启服务 sudo service clickhouse-server restart 测试: bigdata@server01:~$ clickhouse-clientClickHouse client version 18.14.13.Connecting to localhost:9000.Connected to ClickHouse server version 18.14.13 revision 54409. server01 :) select Now(); SELECT Now() ┌───────────────Now()─┐│ 2018-11-09 14:08:21 │└─────────────────────┘ 1 rows in set. Elapsed: 0.010 sec.
最近使用docker装在多台机器上安装clickhouse集群,学习一下docker的基础操作 容器基本操作 1 查看docker信息 sudo docker info2 运行容器 sudo docker run -i -t ubuntu /bin/bash3 在容器中可以安装软件和我们外面的linux机器一样,只是不一样的ubuntu和centos命令不一样4 列出容器 sudo docker ps -a (-a 包括没有运行的)5 启动容器的时候可以给容器命名 sudo docker run --name firstContainername -i -t ubuntu /bin/bash6 停止容器 sudo docker stop firstContainername (restart)7 附着进入容器 sudo docker attach firstContainername8 后台运行容器 sudo docker run -d -i -t ubuntu /bin/bash9 获取容器日志 sudo docker logs firstContainername10 持续跟踪容器日志 sudo docker logs -f firstContainername11 持续跟踪容器日志,并打印时间 sudo docker logs -ft firstContainername12 可以将日志重定向到宿主机,也有一些日期驱动 sudo docker run --logs-driver="syslog" --name firstContainername -d 使用syslog的日志驱动,关于日志驱动百度13 查看容器内的进程 sudo docker to firstContainername14 统计容器的内存,网络,cpu,io等的指标 sudo docker stats firstContainername15 在后台运行的容器内执行命令 sudo docker exec -d firstContainername touch /etc/new_config_file16 进入容器 sudo docker exec -it firstContainername /bin/bash17 停止容易 sudo docker stop firstContainername18 自动重启 sudo docker run --restart=always --name firstContainername -d ubuntu /bin/sh --restart=always 无论什么情况停止都会重启,还可以加参数 --restart=on-failure:5 退出代码为非0时重启5次19 获取容器信息 sudo docker inspect firstContainername20 删除容器 sudo docker rm firstContainername21 删除所有容器 sudo docker rm `sudo docker ps -a -q` -a返回所有容器 -q只返回容器的id 镜像 1 列出所有镜像 sudo docker images2 拉取镜像 sudo docker pull ubuntu 可以指定版本号,不指定为默认最新的镜像3 查找镜像 sudo docker search ubuntu4 注册docker账号后就可以使用 docker login命令进行登录5 可以拉取一个centos镜像 sudo docker pull centos 然后运行 sudo docker run -it --name centosContener centos /bin/bash 进入容器安装vim yum -y install vim 退出容器 exit 提交容器 sudo docker commit -m"信息" -a "作者" centosContener 镜像用户名/仓库名:标签6 查看镜像的信息 sudo docker inspect 镜像用户名/仓库名:标签7 Dockerfile FROM centos RUN yum -y install nginx EXPOSE 80 sudo docker build -t="镜像用户名/仓库名:标签"8 构建镜像时禁用缓存 sudo docker build --no-cache -t="镜像用户名/仓库名:标签"9 查看docker镜像的构建历史 sudo docker history centos 实例 sudo docker history zhaoqinrong/centos:test10 查看容器端口的映射情况 sudo docker port centosContener 80 会返回映射到宿主机上的端口11 端口绑定 sudo docker run --name firstContainername -p 80 -d zhaoqinrong/centos sudo docker run --name firstContainername -p 8080:80 -d zhaoqinrong/centos sudo docker run --name firstContainername -p 127.0.0.1:8080:80 -d zhaoqinrong/centos sudo docker run --name firstContainername -p 映射ip:映射到宿主机的端口:容器端口 -d zhaoqinrong/centos sudo docker run --name firstContainername -p -d zhaoqinrong/centos 将构建镜像中的dockerfile文件中的EXPOSE的所有端口公开,并随机绑定到宿主机的端口上12 Dockerfile 中的CMD命令,RUN命令是在构建中,docker容器未启动时作用,而CMD是在启动后执行的命令 CMD["/bin/bash","-l"] docker网络 1 创建一个docker网络 sudo docker network create app2 sudo docker network inspect app 查看新建网络的信息,包含这个网络中的所有容器3 查看当前系统中的所有网络 sudo docker network ls4 在新创建的app网络中创建容器 sudo docker run -d --net=app --name db zhaoqinrong/centos5 将已有容器添加到app网络 sudo docker network connect app db26 退出app网络 sudo docker network disconnect app db2 还可以学习一下docker-compose和swarm 感觉docker很强大
UPDATE t1 INNER JOIN t2 ON t1.c1=t2.c1 SET t1.c2=value WHERE t1`removed`=0 AND t2`removed`=0 AND t1.c3='[]'
点击查看文章
1.自定义异常类 import lombok.Data; @Data public class UserException extends RuntimeException { private Long id; public UserException(Long id) { super("user not exist"); this.id = id; } public UserException(String message, Long id) { super(message); this.id = id; } } 自定义异常类 2.编写异常处理handler import java.util.HashMap; import java.util.Map; @ControllerAdvice public class ControllerExceptionHandler { @ExceptionHandler(UserException.class) @ResponseBody @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public Map<String,Object> handlerUserNotExistException(UserException ex){ Map<String,Object> result=new HashMap<>(); result.put("id",ex.getId()); result.put("message",ex.getMessage()); return result; } } 异常处理handler 3.使用过程
步骤: 1.定义注解: import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = MyValidatorClass.class) public @interface MyValidator { String message(); Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } 自定义校验注解 2.定义校验类 import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /** * MyValidator,自定义注解 * String 标注在String类型的字段上,传过来的值是String类型 */ public class MyValidatorClass implements ConstraintValidator<MyValidator,String> { /** * 初始化注解时执行的 * @param myValidator */ @Override public void initialize(MyValidator myValidator) { } /** * 真正的校验逻辑 * @param o * @param constraintValidatorContext * @return */ @Override public boolean isValid(String o, ConstraintValidatorContext constraintValidatorContext) { return false; } } 自定义校验逻辑 3.使用
使用步骤: 1.使用接口来声明多个视图 2.在值对象的get方法上指定视图 3.在Controller方法上指定视图
lftp连接ftp在脚本中可以 lftp -c "open username:password@host:port; ls /Friso/20180822/click/mobile/SUCCESS | wc -l" lftp usename:password@host:port -e "ls /Friso/20180823; bye" lftp连接sftp并指定私钥 lftp -e 'set sftp:auto-confirm yes;set sftp:connect-program "ssh -a -x -i <私钥文件>";open sftp://usename:password@host;mirror -eR files:' 如果password不填的话不会跳过验证,指定私钥,密码可以随便写一个
1.(先进入项目文件夹)通过命令 git init 把这个目录变成git可以管理的仓库。 git init 2.把文件添加到版本库中,使用命令 git add .添加到暂存区里面去,不要忘记后面的小数点“.”,意为添加文件夹下的所有文件(夹)。 git add . 3.commit到主分支 git commit -m "描述" 4.登录github,把本地仓库提交至远程仓库。 接下来你要做的就是复制那个地址,然后你将本地仓库个远程仓库连接起来。 git remote add origin git@github.com:yourname/仓库名.git 5.进行第一次提交 git push -u origin master ps: windows系统中使用git时报错“warning: LF will be replaced by CRLF”解决方案: $ rm -rf .git // 删除.git $ git config --global core.autocrlf false //禁用自动转换 //然后重新执行 $ git init $ git add . rm -rf .git慎用!!!!原因详见:https://www.zhihu.com/question/29438735 不小心敲了rm -rf后反应是怎样的? 怕什么真理无穷,进一寸有一寸的欢喜。
自己是直接查出来然后利用set去重(自己感觉不是太好,不过能达到目的) List<CampaignDashboardDimensionDo> list = query.getResultList();Set<CampaignDashboardDimensionDo> set=new HashSet<>(list);如有更好的方法,希望大佬留言,谢谢
spring: datasource: first: type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://xx.xx.xx.xx:xx/xx?characterEncoding=utf8 driver-class-name: com.mysql.jdbc.Driver username: xx password: xx #配置监控统计拦截的filters,去掉监控界面sql将无法统计,'wall'用于防火墙 filters: stat,wall,log4j #最大活跃数 maxActive: 20 #初始化连接数 initialSize: 1 #最大连接等待超过时间 maxWait: 60000 #打开PSCache,并且指定每个连接PSCache的大小 poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 #通过connectionProperties属性来打开mergeSql功能;慢SQL记录 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 1 from dual testWhileIdle: true testOnBorrow: false testOnReturn: false sec: type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://xx.xx.xx.xx:3306/xx?characterEncoding=utf8 driver-class-name: com.mysql.jdbc.Driver username: xx password: xx #配置监控统计拦截的filters,去掉监控界面sql将无法统计,'wall'用于防火墙 filters: stat,wall,log4j #最大活跃数 maxActive: 20 #初始化连接数 initialSize: 1 #最大连接等待超过时间 maxWait: 60000 #打开PSCache,并且指定每个连接PSCache的大小 poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 #通过connectionProperties属性来打开mergeSql功能;慢SQL记录 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 1 from dual testWhileIdle: true testOnBorrow: false testOnReturn: false 配置文件 @ServletComponentScan @Configuration public class DatasourceConfiguration { private Logger logger = LoggerFactory.getLogger(DatasourceConfiguration.class); @Value("${spring.datasource.first.url}") private String firstdevUrl; @Value("${spring.datasource.first.username}") private String firstUsername; @Value("${spring.datasource.first.password}") private String firstPassword; @Value("${spring.datasource.sec.url}") private String secUrl; @Value("${spring.datasource.sec.username}") private String secUsername; @Value("${spring.datasource.sec.password}") private String secPassword; @Value("com.mysql.jdbc.Driver") private String driverClassName; @Value("5") private int initialSize; @Value("5") private int minIdle; @Value("20") private int maxActive; @Value("60000") private int maxWait; /** * 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 */ @Value("60000") private int timeBetweenEvictionRunsMillis; /** * 配置一个连接在池中最小生存的时间,单位是毫秒 */ @Value("300000") private int minEvictableIdleTimeMillis; @Value("SELECT 1 FROM DUAL") private String validationQuery; @Value("true") private boolean testWhileIdle; @Value("false") private boolean testOnBorrow; @Value("false") private boolean testOnReturn; /** * 打开PSCache,并且指定每个连接上PSCache的大小 */ @Value("true") private boolean poolPreparedStatements; @Value("20") private int maxPoolPreparedStatementPerConnectionSize; /** * 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 */ @Value("stat,wall,log4j") private String filters; /** * 通过connectProperties属性来打开mergeSql功能;慢SQL记录 */ @Value("druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500") private String connectionProperties; @Bean(name = "secDatasource") @Qualifier("secDatasource") @ConfigurationProperties(prefix = "spring.datasource.sec") public DataSource secDataSource() { return getDruidDataSource(secUsername, secPassword, secUrl); } @Bean(name = "firstDatasource") @Qualifier("firstDatasource") @Primary @ConfigurationProperties(prefix = "spring.datasource.first") public DataSource firstDataSource() { return getDruidDataSource(firstUsername, firstPassword, firstUrl); } private DruidDataSource getDruidDataSource(String username, String password, String url) { DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(url); datasource.setUsername(username); datasource.setPassword(password); datasource.setDriverClassName(driverClassName); //configuration datasource.setInitialSize(initialSize); datasource.setMinIdle(minIdle); datasource.setMaxActive(maxActive); datasource.setMaxWait(maxWait); datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setValidationQuery(validationQuery); datasource.setTestWhileIdle(testWhileIdle); datasource.setTestOnBorrow(testOnBorrow); datasource.setTestOnReturn(testOnReturn); datasource.setPoolPreparedStatements(poolPreparedStatements); datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); try { datasource.setFilters(filters); } catch (SQLException e) { logger.error("druid configuration initialization filter : {0}", e); } datasource.setConnectionProperties(connectionProperties); return datasource; } } 配置数据源 package com.ipinyou.mip.configuration; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; /** * 这样的方式不需要添加注解:@ServletComponentScan * Created by Administrator on 2018/2/28. */ @Configuration public class DruidConfiguration { @Bean public ServletRegistrationBean statViewServlet(){ //创建Servlet,注册实体 ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); //设置ip白名单 servletRegistrationBean.addInitParameter("allow","xx.xx.xx.xx"); //设置ip黑名单,如果deny和allow共同存在时,deny优先于allow servletRegistrationBean.addInitParameter("deny","xx.xx.xx.xx"); //设置控制台管理用户 servletRegistrationBean.addInitParameter("loginUsername","xxx"); servletRegistrationBean.addInitParameter("loginPassword","xxx"); //是否可以重置数据 servletRegistrationBean.addInitParameter("resetEnable","false"); return servletRegistrationBean; } @Bean public FilterRegistrationBean statFilter(){ //创建过滤器 FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); //设置过滤器过滤路径 filterRegistrationBean.addUrlPatterns("/*"); //忽略过滤形式 filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; } } 设置数据源的过滤器 package com.ipinyou.mip.configuration; import java.util.Map; import javax.persistence.EntityManager; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryPrimary", transactionManagerRef = "transactionManagerPrimary", basePackages = {"xx.xx.xxx","xx.xx.xx"})//设置dao(repo)所在位置 public class JpaConfiguration { @Autowired @Qualifier("firstDatasource") private DataSource firstDataSource; @Primary @Bean(name = "entityManagerFirst") public EntityManager entityManager(EntityManagerFactoryBuilder builder) { return entityManagerFactoryPrimary(builder).getObject().createEntityManager(); } @Autowired private JpaProperties jpaProperties; private Map<String, Object> getVendorProperties() { return jpaProperties.getHibernateProperties(new HibernateSettings()); } /** * 设置实体类所在位置 */ @Primary @Bean(name = "entityManagerFactoryPrimary") public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) { return builder .dataSource(mipdevDataSource) .packages("xx.xx.xx.xx") .properties(getVendorProperties()) .persistenceUnit("firstManageFactory") .properties(getVendorProperties()) .build(); } @Primary @Bean(name = "transactionManagerPrimary") public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject()); } } firstJpaConfiguration package com.ipinyou.mip.configuration; import java.util.Map; import javax.persistence.EntityManager; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactorySec", transactionManagerRef = "transactionManagerSec", basePackages = {"xx.xx.xx"})//设置dao(repo)所在位置 public class JpaSecConfiguration { @Autowired @Qualifier("secDatasource") private DataSource secDatasource; @Bean(name = "entityManagerAmp") public EntityManager entityManager(EntityManagerFactoryBuilder builder) { return entityManagerFactoryAmp(builder).getObject().createEntityManager(); } @Autowired private JpaProperties jpaProperties; private Map<String, Object> getVendorProperties() { return jpaProperties.getHibernateProperties(new HibernateSettings()); } /** * 设置实体类所在位置 */ @Bean(name = "entityManagerFactorySec") public LocalContainerEntityManagerFactoryBean entityManagerFactoryAmp(EntityManagerFactoryBuilder builder) { return builder .dataSource(secDatasource) .packages("xx.xx.xx") .properties(getVendorProperties()) .persistenceUnit("secManageFactory") .properties(getVendorProperties()) .build(); } @Bean(name = "transactionManagerSec") public PlatformTransactionManager transactionManagerAmp(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(entityManagerFactorySec(builder).getObject()); } } secJpaConfiguration package com.ipinyou.mip.configuration; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.jdbc.core.JdbcTemplate; @Configuration @Import(DatasourceConfiguration.class) public class JdbcTemplateConfiguration { @Bean(name = "secJdbcTemplate") public JdbcTemplate primaryJdbcTemplate( @Qualifier("secDatasource") DataSource dataSource) { return new JdbcTemplate(dataSource); } @Bean(name = "firstJdbcTemplate") public JdbcTemplate threeJdbcTemplate( @Qualifier("firstDatasource") DataSource dataSource) { return new JdbcTemplate(dataSource); } } JdbcTemplateConfiguration /** * 提供了一系列数据库查询方法 * * @author guodong.zhang */ public class CommonDao<E, PK extends Serializable> { @PersistenceContext(unitName = "secManageFactory") protected EntityManager em; /** * 相当于jdbctemplate的queryForlist 返回List<Map<String, Object>> * * @param sql * @return */ public List<Map<String, Object>> queryForList(String sql) { Query nativeQuery = em.createNativeQuery(sql); nativeQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); List<Map<String,Object>> resultList = nativeQuery.getResultList(); return resultList; } } 具体使用
SELECT column_type FROM information_schema. COLUMNS WHERE TABLE_SCHEMA = "数据库名" AND DATA_TYPE = 'enum' AND table_name="表明" AND column_name="列名"; 获取到的结果
public class Test(){ @PersistenceContext(unitName = "manageFactory") protected EntityManager em; public List<Map<String, Object>>getListMap(String sql){ Query nativeQuery=em.createNativeQuery(sql); nativeQuery.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); List resultList=nativeQuery.getResultList(); return resultList; } }
git bash各种乱码问题
1.首先看一下我需要导入的数据: 用excel打开的时候显示: 用notepad++打开显示为: 2.使用notepad++打开改变字符集为UTF-8 3,建立表,表中的字段要和文件中的一致 3.执行命令(我的文件放在本地E盘下) LOAD DATA LOCAL INFILE 'E:/IHG_IPY20180405135615_bi.csv' INTO TABLE `IHG_hotel`FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 ROWS;--需要忽略一行,因为我第一行是表头 注意要加local参数,否则没有file权限的用户会报 ERROR 1045 (28000): Access denied FOR USER 'mip'@'%' (USING PASSWORD: YES)这个错误
具体方法请看创始人博客及github
IntelliJ IDEA常见问题解决办法汇总
优点:有效期至2099年,不出意外,这辈子肯定够用了 缺点:稍微麻烦些,不过不要紧,为了以后省事,都值了 下面是具体的破解激活步骤: 1. 下载破解补丁文件,路径为:http://idea.lanyus.com/jar/JetbrainsCrack-2.7-release-str.jar 2.将补丁放在安装包的/bin路径下,如图中放置在最后的jar文件,并且对本文件夹(bin)下的idea.vmoptions配置文件进行修改(可能是版本还是不同操作系统的原因,有人可能没有idea.vmoptions,但是有idea.exe.vmoptions和idea64.exe.vmoptions这两个文件,在这里面进行配置应该也是一样),打开后在最后一行添加如下一条配置指令: windows版:-javaagent:这里放置对应补丁包的路径(比如:D:/indea/bin/JetbrainsCrack-2.7-release-str.jar) Mac版:-javaagent:../bin/JetbrainsCrack-2.7-release-str.jar 3.保存编辑后的文件,然后打开idea,进入激活窗口此时需要选择 激活码 的激活方式,并输入如下激活码进行激活: Activation Code: BIG3CLIK6F-eyJsaWNlbnNlSWQiOiJCSUczQ0xJSzZGIiwibGljZW5zZWVOYW1lIjoibGFuIHl1IiwiYXNzaWduZWVOYW1lIjoiIiwiYXNzaWduZWVFbWFpbCI6IiIsImxpY2Vuc2VSZXN0cmljdGlvbiI6IkZvciBlZHVjYXRpb25hbCB1c2Ugb25seSIsImNoZWNrQ29uY3VycmVudFVzZSI6ZmFsc2UsInByb2R1Y3RzIjpbeyJjb2RlIjoiQUMiLCJwYWlkVXBUbyI6IjIwMTctMTEtMjMifSx7ImNvZGUiOiJETSIsInBhaWRVcFRvIjoiMjAxNy0xMS0yMyJ9LHsiY29kZSI6IklJIiwicGFpZFVwVG8iOiIyMDE3LTExLTIzIn0seyJjb2RlIjoiUlMwIiwicGFpZFVwVG8iOiIyMDE3LTExLTIzIn0seyJjb2RlIjoiV1MiLCJwYWlkVXBUbyI6IjIwMTctMTEtMjMifSx7ImNvZGUiOiJEUE4iLCJwYWlkVXBUbyI6IjIwMTctMTEtMjMifSx7ImNvZGUiOiJSQyIsInBhaWRVcFRvIjoiMjAxNy0xMS0yMyJ9LHsiY29kZSI6IlBTIiwicGFpZFVwVG8iOiIyMDE3LTExLTIzIn0seyJjb2RlIjoiREMiLCJwYWlkVXBUbyI6IjIwMTctMTEtMjMifSx7ImNvZGUiOiJEQiIsInBhaWRVcFRvIjoiMjAxNy0xMS0yMyJ9LHsiY29kZSI6IlJNIiwicGFpZFVwVG8iOiIyMDE3LTExLTIzIn0seyJjb2RlIjoiUEMiLCJwYWlkVXBUbyI6IjIwMTctMTEtMjMifSx7ImNvZGUiOiJDTCIsInBhaWRVcFRvIjoiMjAxNy0xMS0yMyJ9XSwiaGFzaCI6IjQ3NzU1MTcvMCIsImdyYWNlUGVyaW9kRGF5cyI6MCwiYXV0b1Byb2xvbmdhdGVkIjpmYWxzZSwiaXNBdXRvUHJvbG9uZ2F0ZWQiOmZhbHNlfQ==-iygsIMXTVeSyYkUxAqpHmymrgwN5InkOfeRhhPIPa88FO9FRuZosIBTY18tflChACznk3qferT7iMGKm7pumDTR4FbVVlK/3n1ER0eMKu2NcaXb7m10xT6kLW1Xb3LtuZEnuis5pYuEwT1zR7GskeNWdYZ0dAJpNDLFrqPyAPo5s1KLDHKpw+VfVd4uf7RMjOIzuJhAAYAG+amyivQt61I9aYiwpHQvUphvTwi0X0qL/oDJHAQbIv4Qwscyo4aYZJBKutYioZH9rgOP6Yw/sCltpoPWlJtDOcw/iEWYiCVG1pH9AWjCYXZ9AbbEBOWV71IQr5VWrsqFZ7cg7hLEJ3A==-MIIEPjCCAiagAwIBAgIBBTANBgkqhkiG9w0BAQsFADAYMRYwFAYDVQQDDA1KZXRQcm9maWxlIENBMB4XDTE1MTEwMjA4MjE0OFoXDTE4MTEwMTA4MjE0OFowETEPMA0GA1UEAwwGcHJvZDN5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxcQkq+zdxlR2mmRYBPzGbUNdMN6OaXiXzxIWtMEkrJMO/5oUfQJbLLuMSMK0QHFmaI37WShyxZcfRCidwXjot4zmNBKnlyHodDij/78TmVqFl8nOeD5+07B8VEaIu7c3E1N+e1doC6wht4I4+IEmtsPAdoaj5WCQVQbrI8KeT8M9VcBIWX7fD0fhexfg3ZRt0xqwMcXGNp3DdJHiO0rCdU+Itv7EmtnSVq9jBG1usMSFvMowR25mju2JcPFp1+I4ZI+FqgR8gyG8oiNDyNEoAbsR3lOpI7grUYSvkB/xVy/VoklPCK2h0f0GJxFjnye8NT1PAywoyl7RmiAVRE/EKwIDAQABo4GZMIGWMAkGA1UdEwQCMAAwHQYDVR0OBBYEFGEpG9oZGcfLMGNBkY7SgHiMGgTcMEgGA1UdIwRBMD+AFKOetkhnQhI2Qb1t4Lm0oFKLl/GzoRykGjAYMRYwFAYDVQQDDA1KZXRQcm9maWxlIENBggkA0myxg7KDeeEwEwYDVR0lBAwwCgYIKwYBBQUHAwEwCwYDVR0PBAQDAgWgMA0GCSqGSIb3DQEBCwUAA4ICAQC9WZuYgQedSuOc5TOUSrRigMw4/+wuC5EtZBfvdl4HT/8vzMW/oUlIP4YCvA0XKyBaCJ2iX+ZCDKoPfiYXiaSiH+HxAPV6J79vvouxKrWg2XV6ShFtPLP+0gPdGq3x9R3+kJbmAm8w+FOdlWqAfJrLvpzMGNeDU14YGXiZ9bVzmIQbwrBA+c/F4tlK/DV07dsNExihqFoibnqDiVNTGombaU2dDup2gwKdL81ua8EIcGNExHe82kjF4zwfadHk3bQVvbfdAwxcDy4xBjs3L4raPLU3yenSzr/OEur1+jfOxnQSmEcMXKXgrAQ9U55gwjcOFKrgOxEdek/Sk1VfOjvS+nuM4eyEruFMfaZHzoQiuw4IqgGc45ohFH0UUyjYcuFxxDSU9lMCv8qdHKm+wnPRb0l9l5vXsCBDuhAGYD6ss+Ga+aDY6f/qXZuUCEUOH3QUNbbCUlviSz6+GiRnt1kA9N2Qachl+2yBfaqUqr8h7Z2gsx5LcIf5kYNsqJ0GavXTVyWh7PYiKX4bs354ZQLUwwa/cG++2+wNWP+HtBhVxMRNTdVhSm38AknZlD+PTAsWGu9GyLmhti2EnVwGybSD2Dxmhxk3IPCkhKAK+pl0eWYGZWG3tJ9mZ7SowcXLWDFAk0lRJnKGFMTggrWjV8GYpw5bq23VmIqqDLgkNzuoog== 激活码 4.激活成功,查看可知,有效期至2099年,放心使用吧!
大概介绍下流程: 借助idea实现mybatis逆向工程 用xml配置实现整合 用cmd命令行实现mybatis逆向工程 用mapping.xml配置实现数据交互 用注解的方式实现数据交互 首先我的开发环境: jdk1.8+maven3+IDEA 1. mybatis逆向攻城 逆向工程方式很多,我目前接触到的就两种,一种是借助于ide开发工具,一种是在cmd中执行命令。(其实二者原理都一样,都是执行maven的generator命令,具体请看下文)。 1. 完善pom文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>springboot-mybatis</groupId> <artifactId>springboot-mybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot-mybatis</name> <description>Demo project for Spring Boot</description> <parent> <groupId>springboot-integration</groupId> <artifactId>springboot-integration</artifactId> <version>1.0-SNAPSHOT</version> </parent> <!-- Add typical dependencies for a web application --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <!-- alibaba的druid数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.11</version> </dependency> <!-- alibaba的druid数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <!-- 分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.0.4</version> </dependency> </dependencies> <!-- Package as an executable jar --> <build> <finalName>springboot-mybatis</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <testFailureIgnore>true</testFailureIgnore> </configuration> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </build> </project> pom.xml 2. 逆向所需配置文件generatorConfig.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包--> <classPathEntry location="E:\lib\mysql_driver\mysql-connector-java-5.1.26-bin.jar"/> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--数据库链接URL,用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/user" userId="root" password="root"></jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成模型的包名和位置--> <javaModelGenerator targetPackage="com.fantj.sbmybatis.model" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置--> <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.fantj.sbmybatis.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名--> <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration> generatorConfig.xml 3. 利用IDE创建逆向工程启动类 4. add一个Maven configuration 5. 我的数据库和表结构 6. application配置文件 server:port: 8080 spring: datasource: name: test url: jdbc:mysql://127.0.0.1:3306/user username: root password: root # druid 连接池 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20 mybatis: mapper-locations: classpath:mapping/*.xml type-aliases-package: com.fant.model #pagehelper分页插件 pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true params: count=countSql application.yml 运行generator工程 自动生成代码 生成的文件 User.java package com.fantj.model; import java.util.Date; public class User { private Integer id; private String username; private Date birthday; private String sex; private String address; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex == null ? null : sex.trim(); } public String getAddress() { return address; } public void setAddress(String address) { this.address = address == null ? null : address.trim(); } } User.java UserMapper .java package com.fantj.mapper; import com.fantj.model.User; import java.util.List; public interface UserMapper { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); List<User> selectAll(); } userMapper.java UserMapper.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.fantj.mapper.UserMapper"> <resultMap id="BaseResultMap" type="com.fantj.model.User"> <id column="id" property="id" jdbcType="INTEGER"/> <result column="username" property="username" jdbcType="VARCHAR"/> <result column="birthday" property="birthday" jdbcType="DATE"/> <result column="sex" property="sex" jdbcType="CHAR"/> <result column="address" property="address" jdbcType="VARCHAR"/> </resultMap> <sql id="Base_Column_List"> id, username, birthday, sex, address </sql> <select id="selectAll" resultMap="BaseResultMap">select <include refid="Base_Column_List"/> from user </select> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer">select <include refid="Base_Column_List"/> from user where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from user where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.fantj.model.User"> insert into user (id, username, birthday, sex, address) values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{birthday,jdbcType=DATE}, #{sex,jdbcType=CHAR}, #{address,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.fantj.model.User">insert into user <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null">id,</if> <if test="username != null">username,</if> <if test="birthday != null">birthday,</if> <if test="sex != null">sex,</if> <if test="address != null">address,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null">#{id,jdbcType=INTEGER},</if> <if test="username != null">#{username,jdbcType=VARCHAR},</if> <if test="birthday != null">#{birthday,jdbcType=DATE},</if> <if test="sex != null">#{sex,jdbcType=CHAR},</if> <if test="address != null">#{address,jdbcType=VARCHAR},</if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.fantj.model.User">update user <set> <if test="username != null">username = #{username,jdbcType=VARCHAR},</if> <if test="birthday != null">birthday = #{birthday,jdbcType=DATE},</if> <if test="sex != null">sex = #{sex,jdbcType=CHAR},</if> <if test="address != null">address = #{address,jdbcType=VARCHAR},</if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.fantj.model.User"> update user set username = #{username,jdbcType=VARCHAR}, birthday = #{birthday,jdbcType=DATE}, sex = #{sex,jdbcType=CHAR}, address = #{address,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> </mapper> userMapper.xml 修改启动类 逆向生成代码后,我们还需要在启动类上添加一个@MapperScan("com.fantj.mapper")注解,告诉我们的Mapper需要扫描的包,这样就不用每个Mapper上都添加@Mapper注解了 package com.fantj; import com.fantj.util.Params; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @SpringBootApplication @MapperScan("com.fantj.mapper") public class MybatisApplication { public static void main(String[] args) { SpringApplication.run(MybatisApplication.class, args); } } App.java 完善controller和service UserController.java package com.fantj.controller; import com.fantj.model.User; import com.fantj.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.jws.soap.SOAPBinding; import java.util.Date; import java.util.List; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(method = RequestMethod.GET, value = "/delete/{id}") public void delete(@PathVariable("id") int id) { userService.delete(id); } @RequestMapping(method = RequestMethod.POST, value = "/insert") public void insert(User user) { userService.insert(user); } @RequestMapping(method = RequestMethod.POST, value = "/update/{id}") public void update(@RequestParam User user) { userService.update(user); } @RequestMapping(method = RequestMethod.GET, value = "/{id}/select") public User select(@PathVariable("id") int id) { return userService.selectById(id); } @RequestMapping(method = RequestMethod.GET, value = "/selectAll/{pageNum}/{pageSize}") public List<User> selectAll(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize) { return userService.selectAll(pageNum, pageSize); } } UserController.java UserService.java package com.fantj.service; import com.fantj.model.User; import java.util.List; public interface UserService { /** * 删除 */ public void delete(int id); /** * 增加 */ public void insert(User user); /** * 更新 */ public int update(User user); /** * 查询单个 */ public User selectById(int id); /** * 查询全部列表 */ public List<User> selectAll(int pageNum, int pageSize); } UserService.java UserServiceImpl .java package com.fantj.service.impl; import com.fantj.mapper.UserMapper; import com.fantj.model.User; import com.fantj.service.UserService; import com.github.pagehelper.PageHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; /** * 删除 * * @param id */ @Override public void delete(int id) { userMapper.deleteByPrimaryKey(id); } /** * 增加 * * @param user */ @Override public void insert(User user) { userMapper.insert(user); } /** * 更新 * * @param user */ @Override public int update(User user) { return userMapper.updateByPrimaryKey(user); } /** * 查询单个 * * @param id */ @Override public User selectById(int id) { return userMapper.selectByPrimaryKey(id); } /** * 查询全部列表,并做分页 * * @param pageNum 开始页数 * @param pageSize 每页显示的数据条数 */ @Override public List<User> selectAll(int pageNum, int pageSize) { //将参数传给这个方法就可以实现物理分页了,非常简单。 PageHelper.startPage(pageNum,pageSize); return userMapper.selectAll(); } } UserServiceImpl.java 原文地址
点此去
因为学习,在网上找了很多hbase搭建的文章,感觉这篇很好,点此 搭建好后,jps查看了后台进程,发现在slave上面没有HRegionServer进程 便查看了 slave上关于HRegionServer的日志,发现报错 如下 然后网上查了一下,说是时间不同步的问题,自己使用date命令查看了一下系统时间,确实时间不一样 所以又搜索了几篇关于linux时间同步的博客 linux时间同步 这篇文章不错 我用的是time.nuri.net这个时间服务器, 之后再启动就好了,安装很简单
1 pom.xml文件 注:热部署功能spring-boot-1.3开始有的 <!--添加依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <!-- optional=true,依赖不会传递,该项目依赖devtools;之后依赖myboot项目的项目如果想要使用devtools,需要重新引入 --> <optional>true</optional> </dependency> 注:project 中添加 spring-boot-maven-plugin,主要在eclipse中使用,idea中不需要添加此配置。 <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> </plugin> </plugins> </build> 2 更改idea配置 1) “File” -> “Settings” -> “Build,Execution,Deplyment” -> “Compiler”,选中打勾 “Build project automatically” 。 2) 组合键:“Shift+Ctrl+Alt+/” ,选择 “Registry” ,选中打勾 “compiler.automake.allow.when.app.running” 。 3 Chrome禁用缓存 F12或者“Ctrl+Shift+I”,打开开发者工具,“Network” 选项卡下 选中打勾 “Disable Cache(while DevTools is open)”
请看https://www.cnblogs.com/garfieldcgf/p/8119506.html
1.首先安装ntp yum -y install ntp 2.执行命令 ntpdate -u cn.ntp.org.cn
前提:1.机器最好都做ssh免密登录,最后在启动hadoop的时候会简单很多 免密登录看免密登录 2.集群中的虚拟机最好都关闭防火墙,否则很麻烦 3集群中的虚拟机中必须安装jdk. 具体安装步骤如下: 1.将文件拷贝到linux系统中(可以拷贝到所以的虚拟机,也可以拷贝到一台虚拟机,最后进行复制) 2.解压到/usr/local/hadoop ,看你需要安装到哪个目录就解压到哪个目录,解压命令 tar -zxvf ~/hadoop-1.2.1-bin.tar.gz -C /usr/local/hadoop ,解压完成就安装完了 接下来就应该修改配置文件 3.配置namenode和数据存储的位置,修改安装后hadoop-1.1.2下的conf文件夹下的core.site.xml文件 添加如下信息:(配置的namenode的ip和hadoop临时文件的地址) <configuration> <property> <name>fs.default.name</name> <value>hdfs://node05:9000</value> </property> <property> <name>hadoop.tmp.dir</name> <value>/opt/hadoop-1.2</value> </property> </configuration> core-site.xml 4.配置节点数(datanode) 编辑slaves文件 5.配置SecondaryNameNode,编辑masters文件,配置如下: 我一共用了三台虚拟机,node05是我的namenode节点.,node06,node07是我的datanode节点.同时node06也是我的SecondaryNameNode节点 6.配置数据的副本数 编辑hdfs-site.xml文件(副本数应该小于等于datanode的数量) 具体配置如下: <configuration> <property> <name>dfs.replication</name> <value>2</value> </property> </configuration> hdfs-site.xml 7.将我们安装的hadoop复制到其余几台虚拟机中,注意配置文件保持一致,否则会失败 8.格式化namenode,到hadoop安装后的bin目录下执行 ./hadoop namenode -format命令 如果出现Error:JAVA_HOME.....错误 请在hadoop 的conf目录下的hadoop-env.sh文件中配置如下: 9.接下来就可以启动hadoop了 启动的时候,到bin目录下执行 ./start-dfs.sh命令,(因为我这里没有安装hdfs所以执行的这个命令) 10:测试是否成功,在每台虚拟机中输入jps测试是否启动成功 node05:namenode: node06(是datanode也是SecondaryNameNode) node07 datanode: 11,在物理机中,修改hosts文件,将我们的集群的ip和域名添加进去: 访问我们的namenode查看hadoop集群信息 Live Nodes的节点数正确为2 如果Live Nodes的值为0 启动过程中动态查看hadoop的日志文件tail -f /usr/local/hadoop/hadoop-1.1.2/logs/hadoop-root-namenode-node05.log 查看有哪些错误, 如过提示 2018-01-25 20:54:09,903 INFO org.apache.hadoop.hdfs.server.namenode.DecommissionManager: Interrupted Monitorjava.lang.InterruptedException: sleep interrupted 修改/etc/hosts文件
SSH免费登录很简单,如果有用过git的就更简单了 只需要一下两步操作就OK: 1.生成公钥和私钥,在linx上生成公钥和私钥,执行:ssh-keygen 2.执行ssh-copy-id +ip 例如你想免密登录node06这台机器,你执行命令如下:ssh-copy-id node06 就ok
@Test public void poi() throws Exception { InputStream inputStream=new FileInputStream("C:\\Users\\Administrator.SKY-20170602BKZ\\Desktop\\111.xlsx"); //整个excel文件 XSSFWorkbook xssfSheets = new XSSFWorkbook(inputStream); //每行的数据存一个list,然后每页的数据存到一个list List<List<String>> result=new ArrayList<List<String>>(); //遍历XSSFWorkbook是否有多个sheet for (XSSFSheet xss:xssfSheets){ //如果当前sheet为空则开始下一次循环 if (xss==null) continue; //循环当前页 获取每一行 for (int rowNum=1;rowNum<=xss.getLastRowNum();rowNum++){ ArrayList<String> rowlist= new ArrayList<String>(); XSSFRow row = xss.getRow(rowNum); short firstCellNum = row.getFirstCellNum(); short lastCellNum = row.getLastCellNum(); //获取每一个单元格 Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()){ Cell next = cellIterator.next(); next.setCellType(Cell.CELL_TYPE_STRING); rowlist.add(next.getStringCellValue()); } result.add(rowlist); } } System.out.println(result); } 解析代码 原文地址:https://m.aliyun.com/yunqi/articles/369813?spm=a2c41.11123433.0.0 如果poi导入excel表格数据时报出Cannot get a text value from a numeric cell错误 异常描述:在导入excel的时候在获取excel单元格数据的时候会出现Cannot get a text value from a numeric cell的异常抛出。 异常原因:poi读取excel单元格的数据,cell有不同的数据类型(CELL_TYPE_NUMERIC,CELL_TYPE_STRING,CELL_TYPE_FORMULA),如果cell中的数据是数值的话,如果你没有给他设置cell的类型的话。默认会认为是CELL_TYPE_NUMERICl类型,如果从一个NUMBER类型的Cell使用.cell.getStringCellValue()读取出一个字符串就会出错。 解决的方法:在读取数据之前,设置cell的类型为CELL_TYPE_STRING; cell.setCellType(Cell.CELL_TYPE_STRING);
尝试着仔细阅读thinking in java 看到一篇很好的文章http://blog.csdn.net/u011080472/article/details/51330114
1、yum install mysql-community-server 1 2 3 4 5 6 7 Error: Package: mysql-community-libs-5.7.17-1.el7.x86_64 (mysql57-community-dmr) Requires: libc.so.6(GLIBC_2.14)(64bit) Error: Package: mysql-community-client-5.7.17-1.el7.x86_64 (mysql57-community-dmr) Requires: libc.so.6(GLIBC_2.14)(64bit) Error: Package: mysql-community-client-5.7.17-1.el7.x86_64 (mysql57-community-dmr) Requires: libstdc++.so.6(GLIBCXX_3.4.15)(64bit) You could try using --skip-broken to work around the problem 2、到http://ftp.gnu.org/gnu/libc/下载 wget https://dev.mysql.com/get/Downloads/MySQL-5.6/MySQL-5.6.35-1.el7.x86_64.rpm-bundle.tar tar -xzvf MySQL-5.6.35-1.el7.x86_64.rpm-bundle.tar mkdir build cd build ../configure --prefix=/opt/glibc-2.14 make -j4 #-- make -j4 执行时间很长 make install
Git是一个开源的分布式版本控制系统,可以有效、高速的处理从很小到非常大的项目版本管理。而国外的GitHub和国内的Coding都是项目的托管平台。但是在使用Git工具的时候,第一步要学会如何安装git,本教程就手把手教大家如何手动编译安装git。 1、介绍 使用Coding管理项目,上面要求使用的git版本为1.8.0以上,而很多yum源上自动安装的git版本为1.7,所以需要掌握手动编译安装git方法。 2、安装git依赖包 yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel gcc perl-ExtUtils-MakeMaker 3、删除已有的git yum remove git 4、下载git源码 切换到你的包文件存放目录下 cd /usr/src 下载git安装包 wget https://www.kernel.org/pub/software/scm/git/git-2.8.3.tar.gz 解压git安装包 tar -zxvf git-2.8.3.tar.gz cd git-2.8.3 配置git安装路径 ./configure prefix=/usr/local/git/ 编译并且安装 make && make install 查看git版本号 git --version git已经安装完毕 5、将git指令添加到bash中 vi /etc/profile 在最后一行加入 export PATH=$PATH:/usr/local/git/bin 让该配置文件立即生效 source /etc/profile 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。互联网+时代,时刻要保持学习,携手千锋PHP,Dream It Possible。 出自:https://www.cnblogs.com/lijinhui/p/6901220.html
百度经验这篇文章很不错:https://jingyan.baidu.com/article/bad08e1e8e9a9b09c851219f.html
A连B 1.生成公钥和私钥 ssh-keygen2.复制公钥到需要免密登录的服务器上 ssh-copy-id root@192.168.25.175 A连A 2.复制公钥到本机上 ssh-copy-id root@本机ip 问题: 免密登录遇到Are you sure you want to continue connecting (yes/no)?的提示,很烦人,如何去掉? 解决:修改/etc/ssh/ssh_config将其中的# StrictHostKeyChecking ask 改成 StrictHostKeyChecking no
1.管理(存储和读取)程序提交的状态数据 2.为用户程序提供数据节点监听服务
1.redis安装 Redis是c语言开发的。 安装redis需要c语言的编译环境。如果没有gcc需要在线安装。yum install gcc-c++ 安装步骤: 第一步:redis的源码包上传到linux系统。 第二步:解压缩redis。 第三步:编译。进入redis源码目录。make 第四步:安装。make install PREFIX=/usr/local/redis PREFIX参数指定redis的安装目录。一般软件安装到/usr目录下 详细安装步骤,以及后台运行的配置 点此 linux上安装redis 2.Redis-cli 客户端连接redis 找到安装redis的文件夹中的bin目录.执行以下命令 [root@localhost bin]# ./redis-cli 默认连接localhost运行在6379端口的redis服务。 [root@localhost bin]# ./redis-cli -h 192.168.25.153 -p 6379 -h:连接的服务器的地址 -p:服务的端口号 关闭redis:[root@localhost bin]# ./redis-cli shutdown 3.Redis五种数据类型 redis五种数据类型及命令操作 点此 reids基本命令 4.Redis的持久化方案 redis持久化方法点此 redis持久化方案 5.Redis集群的搭建 5.1 redis-cluster架构图 redis的每个节点上都保存有其他节点的信息,并且相互通信,客户端连接集群时,随机连接 5.2redis-cluster投票:容错 1. redis每个节点之间每隔一段时间就会相互的ping一下,对方收到ping后会回复pong,如上图,如果黄色的节点ping红色的节点时,红色节点没给回复,黄色节点就会以为红色节点已经挂了,接着其他节点去ping红色节点,如果多数节点没有收到回信,则判断红色节点已挂,投票容错就这样. 2. 因为redis的投票容错机制,所以redis的集群至少应该有三个及以上的节点 3.Redis 集群中内置了 16384 个哈希槽,当需要在 Redis 集群中放置一个 key-value 时,redis 先对 key 使用 crc16 算法算出一个结果,然后把结果对 16384 求余数,这样每个 key 都会对应一个编号在 0-16383 之间的哈希槽,redis 会根据节点数量大致均等的将哈希槽映射到不同的节点如下图,所以理论上redis的节点可以有16384个 5.3. Redis集群的搭建 Redis集群中至少应该有三个节点。要保证集群的高可用,需要每个节点有一个备份机。 redis主从复制 如果使用ruby搭建redis集群,从节点不用手动配置,ruby会自动分配 Redis集群至少需要6台服务器(3台是主节点,3台是对应的备份节点)。 搭建伪分布式。可以使用一台虚拟机运行6个redis实例。需要修改redis的端口号7001-7006 5.3.1. 集群搭建环境 1、使用ruby脚本搭建集群。需要ruby的运行环境。 安装ruby yum install ruby yum install rubygems 2、安装ruby脚本运行使用的包。 [root@localhost ~]# gem install redis-3.0.0.gem Successfully installed redis-3.0.0 1 gem installed Installing ri documentation for redis-3.0.0... Installing RDoc documentation for redis-3.0.0... [root@localhost ~]# 在redis解压文件夹的src目录下有一个redis-trib.rb文件之后需要用 [root@localhost ~]# cd redis-3.0.0/src [root@localhost src]# ll *.rb -rwxrwxr-x. 1 root root 48141 Apr 1 2015 redis-trib.rb 5.3.1. 搭建步骤 需要6台redis服务器。搭建伪分布式。 需要6个redis实例。 需要运行在不同的端口7001-7006 第一步:创建6个redis实例,将我们之前安装的redis中的bin目录拷贝六份,并改好名称.修改每个实例运行的端口。需要修改redis.conf配置文件。配置文件中还需要把cluster-enabled yes前的注释去掉(表示是支持集群)。 第二步:启动每个redis实例。这里可以创建一个sh脚本,运行脚本来启动六个redis 脚本内容如下 . 第三步:使用ruby脚本搭建集群。将redis解压文件夹的src目录下有一个redis-trib.rb文件复制到我们放redis集群的文件夹中,使用以下命令 --replicas 1 表示每个节点有一个备份机 ./redis-trib.rb create --replicas 1 192.168.25.153:7001 192.168.25.153:7002 192.168.25.153:7003 192.168.25.153:7004 192.168.25.153:7005 192.168.25.153:7006 ruby搭建集群命令 运行命令后 6. 集群的使用方法 redis连接集群(单机版的不用加参数 -c) [root@localhost redis-cluster]# redis01/redis-cli -p 7002 -c -c:代表连接的是redis集群 redis连接redis单机版和集群版,点此 redis连接redis单机版和集群版 7.业务中使用redis进行缓存 redis不适用于大数据,适用于高并发的程序 1.查询内容列表时添加缓存。 1、查询数据库之前先查询缓存。 2、查询到结果,直接响应结果。 3、查询不到,缓存中没有需要查询数据库。 4、把查询结果添加到缓存中。 5、返回结果。 一般都使用hash数据类型,使用hash时,可以将保存的内容进行归类 INDEX_CONTENT分类 cid hash的字段 JsonUtils.objectToJson(tbContents) cid对应的值 jedisClient.hset(INDEX_CONTENT,cid+"", JsonUtils.objectToJson(tbContents));2.缓存同步 我们在对数据库进行增删改的时候缓存中的数据没有变化,显然这种情况下,下一次查询出来的数据肯定错误,所以需要对缓存进行同步 对内容信息做增删改操作后只需要把对应缓存删除即可。 可以根据我们hash的字段来删除对应的缓存。
集合框架(collections framework) 1.两大基类Collection与Map 1).public interface Collection<E>extends Iterable<E>:Collection表示一组纯数据 Collection继承自Iterable接口,而Iterable接口中提供有能直接获取iterator对象的方法,所以所有继承自Iterable的集合都可以使用iterator迭代 2)Map表示一组key-value对 一般继承自Collection或Map的集合类,会提供两个“标准”的构造函数: 没有参数的构造函数,创建一个空的集合类 有一个类型与基类(Collection或Map)相同的构造函数,创建一个与给定参数具有相同元素的新集合类因为接口中不能包含构造函数,所以上面这两个构造函数的约定并不是强制性的,但是在目前的集合框架中,所有继承自Collection或Map的子类都遵循这一约定。 Collection的继承架构 这里只给出了比较常用的类 如上图所示,Collection类主要有三个接口: Set表示不允许有重复元素的集合(但是可以为null)(A collection that contains no duplicate elements) List表示允许有重复元素的集合(An ordered collection (also known as a sequence)) Queue JDK1.5新增,与上面两个集合类主要是的区分在于Queue主要用于存储数据,而不是处理数据。(A collection designed for holding elements prior to processing.) map的继承架构 Map并不是一个真正意义上的集合(are not true collections),但是这个接口提供了三种“集合视角”(collection views ),使得可以像操作集合一样操作它们,具体如下: map的内容看作key的集合(map’s contents to be viewed as a set of keys 把map的内容看作value的集合(map’s contents to be viewed as a collection of values) Map<String,String> map = new HashMap<String,String>(); map.put("01", "zhangsan"); map.put("02", "lisi"); map.put("03", "wangwu"); Set<String> keySet = map.keySet();//先获取map集合的所有键的Set集合 Iterator<String> it = keySet.iterator();//有了Set集合,就可以获取其迭代器。 while(it.hasNext()){ String key = it.next(); String value = map.get(key);//有了键可以通过map集合的get方法获取其对应的值。 System.out.println("key: "+key+"-->value: "+value);//获得key和value值 } 通过keyset()迭代 把map的内容看作key-value映射的集合(map’s contents to be viewed as a set of key-value mappings) Map<String,String> map = new HashMap<String,String>(); map.put("01", "zhangsan"); map.put("02", "lisi"); map.put("03", "wangwu"); Collection<String> collection = map.values();//返回值是个值的Collection集合 System.out.println(collection); 使用values()遍历 把map的内容看作key-value映射的集合(map’s contents to be viewed as a set of key-value mappings) Map<String,String> map = new HashMap<String,String>(); map.put("01", "zhangsan"); map.put("02", "lisi"); map.put("03", "wangwu"); //通过entrySet()方法将map集合中的映射关系取出(这个关系就是Map.Entry类型) Set<Map.Entry<String, String>> entrySet = map.entrySet(); //将关系集合entrySet进行迭代,存放到迭代器中 Iterator<Map.Entry<String, String>> it2 = entrySet.iterator(); while(it2.hasNext()){ Map.Entry<String, String> me = it2.next();//获取Map.Entry关系对象me String key2 = me.getKey();//通过关系对象获取key String value2 = me.getValue();//通过关系对象获取value System.out.println("key: "+key2+"-->value: "+value2); } 通过entrySet()遍历,推荐使用此方式,性能最高 hashMap public class HashMap<K,V>extends AbstractMap<K,V>implements Map<K,V>, Cloneable, Serializable特点: 线程非安全,并且允许key与value都为null值,HashTable与之相反,为线程安全,key与value都不允许null值。 不保证其内部元素的顺序,而且随着时间的推移,同一元素的位置也可能改变(resize的情况) put、get操作的时间复杂度为O(1)。 遍历其集合视角的时间复杂度与其容量(capacity,槽的个数)和现有元素的大小(entry的个数)成正比,所以如果遍历的性能要求很高,不要把capactiy设置的过高或把平衡因子(load factor,当entry数大于capacity*loadFactor时,会进行resize,reside会导致key进行rehash)设置的过低。 由于HashMap是线程非安全的,这也就是意味着如果多个线程同时对一hashmap的集合试图做迭代时有结构的上改变(添加、删除entry,只改变entry的value的值不算结构改变),那么会报ConcurrentModificationException,专业术语叫fail-fast,尽早报错对于多线程程序来说是很有必要的。 Map m = Collections.synchronizedMap(new HashMap(...)); 通过这种方式可以得到一个线程安全的map。 TreeMap public class TreeMap<K,V>extends AbstractMap<K,V>implements NavigableMap<K,V>, Cloneable, Serializable
关系型数据库: RDBMS RDBMS(Relational Database Management System) 指的是关系型数据库管理系统。 sql语句以分号结束,并且对大小写不敏感 DML语句组成 SELECT - 从数据库表中获取数据 SELECT 列名称 FROM 表名称 UPDATE - 更新数据库表中的数据 DELETE - 从数据库表中删除数据 INSERT INTO - 向数据库表中插入数据 DDL语句组成 CREATE DATABASE - 创建新数据库 ALTER DATABASE - 修改数据库 CREATE TABLE - 创建新表 ALTER TABLE - 变更(改变)数据库表 DROP TABLE - 删除表 CREATE INDEX - 创建索引(搜索键) DROP INDEX - 删除索引
单机版 1.入门实例 @Test public void testJedis(){ //创建一个jedis对象,需要指定服务的ip和端口号 Jedis jedis=new Jedis("192.168.25.11",6379); //直接操作数据库 jedis.set("str","nihao"); //关闭 jedis.close(); } 存值 @Test public void testGetJedis(){ //创建一个jedis对象,需要指定服务的ip和端口号 Jedis jedis=new Jedis("192.168.25.11",6379); //直接操作数据库 String str = jedis.get("str"); System.out.println(str); //关闭 jedis.close(); } 取值 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <jedis.version>2.7.2</jedis.version> </dependency> pom依赖 这样使用的话,每次都需要创建连接和关闭连接,耗费性能,所以一般实际项目中我们一般会采用连接池的方式进行开发 2.使用数据库连接池的方式操作redis @Test public void testJedisPool(){ //创建连接池(单例),需要指定服务ip和端口号 JedisPool pool=new JedisPool("192.168.25.11",6379); //从连接池中获得连接 Jedis resource = pool.getResource(); //使用Jedis操作数据库(方法级别使用) String str = resource.get("str"); System.out.println(str); //一定要关闭Jedis连接 resource.close(); //系统关闭前关闭连接池 pool.close(); } 使用数据库连接池的方式操作redis 集群版 1.直接使用 public void testRedisCluster() { //创建一个JedisCluster对象,构造参数Set类型,集合中每个元素 是一个HostAndPort类型 Set<HostAndPort> nodes=new HashSet<>(); nodes.add(new HostAndPort("192.168.25.11",7001)); nodes.add(new HostAndPort("192.168.25.11",7002)); nodes.add(new HostAndPort("192.168.25.11",7003)); nodes.add(new HostAndPort("192.168.25.11",7004)); nodes.add(new HostAndPort("192.168.25.11",7005)); nodes.add(new HostAndPort("192.168.25.11",7006)); JedisCluster jedisCluster=new JedisCluster(nodes); //直接使用JedisCluster操作redis,自带连接池,JedisCluster可以是单例的 jedisCluster.set("nihao","你好"); System.out.println(jedisCluster.get("nihao")); //系统关闭前,关闭JedisCluster. jedisCluster.close(); } 连接redis集群 使用Spring整合redis集群 <bean class="redis.clients.jedis.JedisCluster" id="jedisCluster"> <constructor-arg name="nodes"> <set> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="192.168.25.11"/> <constructor-arg name="port" value="7001"/> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="192.168.25.11"/> <constructor-arg name="port" value="7002"/> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="192.168.25.11"/> <constructor-arg name="port" value="7003"/> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="192.168.25.11"/> <constructor-arg name="port" value="7004"/> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="192.168.25.11"/> <constructor-arg name="port" value="7005"/> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="192.168.25.11"/> <constructor-arg name="port" value="7006"/> </bean> </set> </constructor-arg> </bean> <bean class="com.taotao.jedis.JedisClientCluster" id="jedisCluster"/> Spring配置文件中配置集群信息和客户端 private JedisCluster jedisCluster; @Before public void testBefore(){ ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("Spring/applicationContext-redis.xml"); jedisCluster=classPathXmlApplicationContext.getBean(JedisCluster.class); } @Test public void testJedisSping(){ jedisCluster.set("11","11"); System.out.println( jedisCluster.get("11")); } 测试代码
一、异常的架构: Throwable类:所以异常类都是Throwable的子类,它派生两个子类 Error和Exception。 Error类:表示仅靠程序本身无法恢复的的严重错误,比如内存溢出,虚拟机错误等,这些异常除了尽力使程序安全退出外,我们并没有办法去解决,所以开发的时候我们更应该关注的是Exception Exception类:由java应用程序抛出和处理的非严重错误,如文件找不到,网络连接中断,数组下标越界等,它的不同的子类分别对应不同类型的异常 运行时异常:包括RuntimeException类及其子类,不要求程序员必须对它们做出处理,如果程序发生运行时异常,而我们并没有处理,会输出异常的堆栈信息,并终止程序运行 Checked异常(非运行时异常):除了运行时异常外的其他由Exception继承来的异常类,程序必须捕获或者声明抛出这种异常。否则程序无法编译通过,如如IOException、SQLException等异常 二、自定义异常的步骤: 当JDK提供的异常类型不能满足程序的需求时,我们可以自定义异常 1.定义一个普通类,并继承exception或RuntimeExceprion,继承Exceprtion的自定义异常为Checked异常(必须抛出或者try cacth),继承自RuntimeExceprion的自定义异常类为运行时异常 2.编写异常类的构造方法,并继承父类实现,常见的如下: /** * 自定义异常类 */ public class MyException extends Exception { public MyException() { } public MyException(String message) { super(message); } /** * * @param message 需要显示的异常信息 * @param cause 为Throwable或其子类的实例 */ public MyException(String message, Throwable cause) { super(message, cause); } public MyException(Throwable cause) { super(cause); } } 继承自Exception的自定义异常类 @Test public void getMessage() throws Exception { try { int a= 10/0; } catch (Exception e) { throw new MyException("10不能除以0"); } } 继承自Exception的异常类的测试 除了继承自Exception还可以继承RuntimeException,具体例子就不往下写了 三、throw和throws的区别 主要区别有以下三点: 1、作用不同:throw用于在程序中抛出异常;throws用于在该方法内抛出了异常; 2、使用的位置不同:throw位于方法体内,可以作为单独语句使用;throws必须跟在方法参数列表的后面,不能单独使用; 3、内容不容:throw抛出一个异常对象,而且只能是一个;throws后面跟异常类,而且可以跟多个异常类
最近在用mybatis,之前用过ibatis,总体来说差不多,不过还是遇到了不少问题,再次记录下, 比如说用#{},和 ${}传参的区别, 使用#传入参数是,sql语句解析是会加上"",比如 select * from table where name = #{name} ,传入的name为小李,那么最后打印出来的就是 select * from table where name = ‘小李',就是会当成字符串来解析,这样相比于$的好处是比较明显对的吧,#{}传参能防止sql注入,如果你传入的参数为 单引号',那么如果使用${},这种方式 那么是会报错的, 另外一种场景是,如果你要做动态的排序,比如 order by column,这个时候务必要用${},因为如果你使用了#{},那么打印出来的将会是 select * from table order by 'name' ,这样是没用, 目前来看,能用#就不要用$, mybatis中的#和$的区别 1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by "111", 如果传入的值是id,则解析成的sql为order by "id". 2. $将传入的数据直接显示生成在sql中。如:order by $user_id$,如果传入的值是111,那么解析成sql时的值为order by user_id, 如果传入的值是id,则解析成的sql为order by id. 3. #方式能够很大程度防止sql注入。 4.$方式无法防止Sql注入。 5.$方式一般用于传入数据库对象,例如传入表名. 6.一般能用#的就别用$. MyBatis排序时使用order by 动态参数时需要注意,用$而不是# 字符串替换 默认情况下,使用#{}格式的语法会导致MyBatis创建预处理语句属性并以它为背景设置安全的值(比如?)。这样做很安全,很迅速也是首选做法,有时你只是想直接在SQL语句中插入一个不改变的字符串。比如,像ORDER BY,你可以这样来使用: ORDER BY ${columnName} 这里MyBatis不会修改或转义字符串。 重要:接受从用户输出的内容并提供给语句中不变的字符串,这样做是不安全的。这会导致潜在的SQL注入攻击,因此你不应该允许用户输入这些字段,或者通常自行转义并检查。 Mybatis中$和#的区别简单小结 前不久,有人来我们公司面试,我们的经理问道了这个问题,我也是一知半解,所以就去百度了一番。 其实区别很简单的,举个例子大家就会明白的。写一句SQL-例如:select * from user_role where user_code = "100"; 这句话而言,需要写成 select * from ${tableName} where user_code = #{userCode} 所以,$符是直接拼成sql的 ,#符则会以字符串的形式 与sql进行拼接。
修改前 <insert id="insert" parameterType="com.taotao.pojo.TbContent" > insert into tb_content (id, category_id, title, sub_title, title_desc, url, pic, pic2, created, updated, content) values (${id,jdbcType=BIGINT}, ${categoryId,jdbcType=BIGINT}, ${title,jdbcType=VARCHAR}, ${subTitle,jdbcType=VARCHAR}, ${titleDesc,jdbcType=VARCHAR}, ${url,jdbcType=VARCHAR}, ${pic,jdbcType=VARCHAR}, ${pic2,jdbcType=VARCHAR}, ${created,jdbcType=TIMESTAMP}, ${updated,jdbcType=TIMESTAMP},${content,jdbcType=LONGVARCHAR}) </insert> 修改后 <insert id="insert" parameterType="com.taotao.pojo.TbContent" > insert into tb_content (id, category_id, title, sub_title, title_desc, url, pic, pic2, created, updated, content) values (#{id,jdbcType=BIGINT}, #{categoryId,jdbcType=BIGINT}, #{title,jdbcType=VARCHAR}, #{subTitle,jdbcType=VARCHAR}, #{titleDesc,jdbcType=VARCHAR}, #{url,jdbcType=VARCHAR}, #{pic,jdbcType=VARCHAR}, #{pic2,jdbcType=VARCHAR}, #{created,jdbcType=TIMESTAMP}, #{updated,jdbcType=TIMESTAMP}, #{content,jdbcType=LONGVARCHAR}) </insert> 主要是#{}和${}的区别 如果不懂的可以点击查看Mybatis中#{}和${}传参的区别及#和$的区别小结
1) 重启后生效 开启: chkconfig iptables on 关闭: chkconfig iptables off 2) 即时生效,重启后失效 开启: service iptables start 关闭: service iptables stop 需要说明的是对于Linux下的其它服务都可以用以上命令执行开启和关闭操作。 开放端口的方法: 方法一:命令行方式 1. 开放端口命令: /sbin/iptables -I INPUT -p tcp --dport 8080 -j ACCEPT 2.保存:/etc/rc.d/init.d/iptables save 3.重启服务:/etc/init.d/iptables restart 4.查看端口是否开放:/sbin/iptables -L -n 方法二:直接编辑/etc/sysconfig/iptables文件 1.编辑/etc/sysconfig/iptables文件:vi /etc/sysconfig/iptables 加入内容并保存:-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8080 -j ACCEPT 2.重启服务:/etc/init.d/iptables restart 3.查看端口是否开放:/sbin/iptables -L -n 但是我用方法一一直保存不上,查阅网上发现直接修改文件不需要iptables save,重启下iptables 重新加载下配置。iptables save 是将当前的iptables写入到/etc/sysconfig/iptables。我不save直接restart也不行,所以还是方法二吧 查询端口是否有进程守护用如下命令grep对应端口,如80为端口号 例:netstat -nalp|grep 80
From 192.168.25.133 icmp_seq=238 Destination Host Unreachable 虚拟机ping主机不通,但是主机可以ping通虚拟机,虚拟机ping不通外网 如果是使用net8模式 我的问题是物理机没有开启服务 将本地服务启动就可以了
原文:http://www.bubuko.com/infodetail-2250226.html 项目中用dubbo发生: Failed to check the status of the service com.taotao.service.ItemService. No provider available for the service 原因: Dubbo缺省会在启动时检查依赖的服务是否可用,不可用时会抛出异常,阻止Spring初始化完成,以便上线时,能及早发现问题,默认check=true。 如果你的Spring容器是懒加载的,或者通过API编程延迟引用服务,请关闭check,否则服务临时不可用时,会抛出异常,拿到null引用,如果check=false,总是会返回引用,当服务恢复时,能自动连上。 可以通过check="false"关闭检查,比如,测试时,有些服务不关心,或者出现了循环依赖,必须有一方先启动。 1、关闭某个服务的启动时检查:(没有提供者时报错) <dubbo:reference interface="com.foo.BarService" check="false" /> 2、关闭所有服务的启动时检查:(没有提供者时报错) 写在定义服务消费者一方 <dubbo:consumer check="false" /> 3、关闭注册中心启动时检查:(注册订阅失败时报错) <dubbo:registry check="false" />
打开网页报错: Ambiguous mapping. Cannot map 'handController' method public com.smallchill.core.toolbox.ajax.AjaxResult com.smallchill.smtlamp.controller.HandController.AC2off(java.lang.String) to {[/hand/AC1off]}: There is already 'handController' bean method public com.smallchill.core.toolbox.ajax.AjaxResult com.smallchill.smtlamp.controller.HandController.AC1off(java.lang.String) mapped. 解决办法: @RequestMapping()中的url重复了,修改为不同的url即可;
1.修改远程仓库的位置(maven默认仓库是国外,所以我们下载jar包很慢) 找到我们安装的maven路径下的conf文件夹下的settings.xml文件 将文件复制到 C:\Users\Administrator\.m2\下 ,修改文件中的仓库位置,我用的是阿里云的一个镜像仓库 <mirror> <id>mirrorId</id> <mirrorOf>repositoryId</mirrorOf> <name>Human Readable Name for this Mirror.</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> </mirror> maven镜像仓库配置 2.设置archetypeCatalog=local(下面有图示) 1.由于默认情况下,根据archetype创建maven项目会从网络下载catalog文件,导致创建maven项目缓慢 Searching for remote catalog: http://repo1.maven.org/maven2/archetype-catalog.xml 2.解决办法可以设置使用本地catalog文件,在IDEA中设置archetype的使用方式为local; -DarchetypeCatalog=local 直接使用360浏览器新建一个下载项 将archetypeCatalog的下载地址复制进去 下载后放到哪里呢,这里与本地仓库的位置有关,假如本地仓库是maven默认的,并没有修改 那么就需要放到 C:\Users\del-berlin\.m2\repository\org\apache\maven\archetype\archetype-catalog\2.4\下 ,本地仓库的默认位置:Default: ${user.home}/.m2/repository 选择defalut Settings进行设置,否则你设置的是你当前项目