迫于好久没写博客心慌慌,随便写个简单版的笔记便于查阅。

新建项目

新建项目 然后起名 继续next netx finish。

首先附上demo的项目结构图

配置pom.xml

<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version> <!-- 我这里用的1.5.9 -->
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.blaze</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</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>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>1.5.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.didispace</groupId>
<artifactId>spring-boot-starter-swagger</artifactId>
<version>1.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency> <!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<!-- druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!--tomcat-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!--<version>1.2.4.RELEASE</version>-->
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.50</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<finalName>blaze</finalName>
</build> </project>

构建demo目录结构

application.properties改成application.yml格式的配置文件

server:
port: 8080 spring:
datasource:
name: mysql_test
type: com.alibaba.druid.pool.DruidDataSource
#druid相关配置
druid:
#监控统计拦截的filters
filters: stat
driver-class-name: com.mysql.jdbc.Driver
#基本属性
url: jdbc:mysql://localhost:3306/blaze_test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username: root
password: root
#配置连接池 初始化大小/最小/最大
initial-size: 1
min-idle: 1
max-active: 20
#获取连接等待超时时间
max-wait: 60000
#间隔多久进行一次检测,检测需要关闭的空闲连接
time-between-eviction-runs-millis: 60000
#一个连接在池中最小生存的时间
min-evictable-idle-time-millis: 300000
validation-query: SELECT 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
#打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
pool-prepared-statements: false
max-pool-prepared-statement-per-connection-size: 20
#redis相关配置 host把端口加进去(详见RedisConfig的jedisConnectionFactory)
redis:
database: 0
host: 193.168.10.102:6379
port: 6379
password:
timeout: 500
pool:
max-idle: 8
max-wait: -1
max-active: 8
min-idle: 0 #mybatis:
# mapper-locations: classpath:mapper/*.xml
# type-aliases-package: com.blaze.model #pagehelper
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
returnPageInfo: check #swagger
swagger:
title: spring-boot-starter-swagger
description: Starter for swagger 2.x
version: 1.1.0.RELEASE
license: Apache License, Version 2.0
license-url: https://www.apache.org/licenses/LICENSE-2.0.html
terms-of-service-url: https://github.com/github-sun/Funs
base-package: com.blaze.demo
contact:
name: blaze
email: 279790279@qq.com

UserDomain.java

package com.blaze.demo.model;

import java.io.Serializable;

/**
* create by zy 2019/5/30 10:35
* TODO
*/
public class UserDomain implements Serializable {
private int id;
private String userId;
private String userName; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUserId() {
return userId;
} public void setUserId(String userId) {
this.userId = userId;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
}
}

UserDao.java

package com.blaze.demo.dao;

import com.blaze.demo.model.UserDomain;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.springframework.transaction.annotation.Transactional; import java.util.List; /**
* create by zy 2019/5/30 10:28
* TODO
*/
@Mapper
public interface UserDao {
//新增user 如果已经存在相同的userName 则不插入数据
@Insert("INSERT INTO tb_user(id,user_id,user_name) SELECT #{id}, #{userId},#{userName} FROM DUAL WHERE NOT EXISTS (SELECT user_name FROM tb_user WHERE user_name=#{userName})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
@Transactional
int insert(UserDomain record); //查询
@Select("SELECT id, user_id as userId, user_name as userName FROM tb_user")
List<UserDomain> selectUsers();
}

UserService.java

package com.blaze.demo.service;

import com.blaze.demo.model.UserDomain;
import com.github.pagehelper.PageInfo; /**
* create by zy 2019/5/30 10:30
* TODO
*/
public interface UserService {
/**
* 新增user
* @param user
* @return
*/
int addUser(UserDomain user); /**
* 分页查询userList
* @param pageNum
* @param pageSize
* @return
*/
PageInfo<UserDomain> findAllUser(int pageNum, int pageSize);
}

UserServiceImpl.java

package com.blaze.demo.service.impl;

import com.blaze.demo.dao.UserDao;
import com.blaze.demo.model.UserDomain;
import com.blaze.demo.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; /**
* create by zy 2019/5/30 10:28
* TODO
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;//这里会报错,但是并不会影响 @Override
public int addUser(UserDomain user) { return userDao.insert(user);
} /*
* 这个方法中用到了我们开头配置依赖的分页插件pagehelper
* 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可;
* pageNum 开始页数
* pageSize 每页显示的数据条数
* */
@Override
public PageInfo<UserDomain> findAllUser(int pageNum, int pageSize) {
//将参数传给这个方法就可以实现物理分页了,非常简单。
PageHelper.startPage(pageNum, pageSize);
List<UserDomain> userDomains = userDao.selectUsers();
PageInfo result = new PageInfo(userDomains);
return result;
}
}

UserController.java

package com.blaze.demo.controller;

import com.blaze.demo.model.UserDomain;
import com.blaze.demo.service.UserService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; /**
* create by zy 2019/5/30 10:28
* TODO
* CrossOrigin 允许跨域访问
*/
@Api(value = "", tags = {"用户管理接口"})
@CrossOrigin(maxAge = 3600, origins = "*")
@RestController
@RequestMapping(value = "/user")
public class UserController {
private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
private UserService userService; @ResponseBody
@PostMapping("/add")
public int addUser(UserDomain user) {
logger.info("-------------blaze add user--------------");
return userService.addUser(user);
} @ResponseBody
@GetMapping("/all")
public Object findAllUser(
@RequestParam(name = "pageNum", required = false, defaultValue = "1")
int pageNum,
@RequestParam(name = "pageSize", required = false, defaultValue = "10")
int pageSize) {
logger.info("-------------blaze select user--------------");
return userService.findAllUser(pageNum, pageSize);
}
}

DemoApplication.java

package com.blaze.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2; /**
* 此处加上@EnableSwagger2注解 才能使用swagger
* 加上@EnableCaching 使用redis
*/
@SpringBootApplication
@EnableSwagger2
@EnableCaching
public class DemoApplication { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} }

集成使用redis

配置在application.yml中

RedisConfig.java

package com.blaze.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig; import java.util.HashMap;
import java.util.Map; /**
* create by zy 2019/5/30 14:19
* TODO
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
private Logger logger = LoggerFactory.getLogger(this.getClass()); @Value("${spring.redis.host}")
private String host; @Value("${spring.redis.port}")
private int port; @Value("${spring.redis.timeout}")
private int timeout; @Value("${spring.redis.pool.max-idle}")
private int maxIdle; @Value("${spring.redis.pool.max-wait}")
private long maxWaitMillis; @Value("${spring.redis.password}")
private String password; @Bean
public JedisPoolConfig getJedisPoolConfig() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
return jedisPoolConfig;
} @Bean
public JedisConnectionFactory jedisConnectionFactory() { if (host.split(",").length == 1) {
//单机版
logger.info("-----------------blaze redis 单机版-------------------------");
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host.split(":")[0]);
factory.setPort(Integer.valueOf(host.split(":")[1]));
factory.setPassword(password);
factory.setTimeout(timeout);
factory.setPoolConfig(getJedisPoolConfig());
return factory;
} else {
//集群
logger.info("-----------------blaze redis 集群版-------------------------");
JedisConnectionFactory jcf = new JedisConnectionFactory(getClusterConfiguration());
jcf.setPoolConfig(getJedisPoolConfig());
jcf.setPassword(password); //集群的密码认证
return jcf;
}
} @Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
logger.info("===cacheManager successed");
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
redisCacheManager.setDefaultExpiration(1800);//秒
return redisCacheManager;
} @Bean(name = "redisTemplate")
public RedisTemplate<String, Object> getRedisTemplate() {
logger.info("===redisTemplate successed");
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
} @Bean
public RedisClusterConfiguration getClusterConfiguration() {
if (host.split(",").length > 1) {
//如果是host是集群模式的才进行以下操作
Map<String, Object> source = new HashMap<String, Object>();
source.put("spring.redis.cluster.nodes", host);
source.put("spring.redis.cluster.timeout", timeout);
//source.put("spring.redis.cluster.max-redirects", redirects);
source.put("spring.redis.cluster.password", password);
return new RedisClusterConfiguration(new
MapPropertySource("RedisClusterConfiguration", source));
} else {
return null;
}
} }

RedisCommon.java

package com.blaze.demo.utils;

import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit; /**
* create by zy 2019/5/30 14:33
* TODO 随便写的 有点简单粗暴 凑合看吧
*/
public class RedisCommon {
@Resource
private RedisTemplate redisTemplate; public RedisCommon(RedisTemplate client) {
this.redisTemplate = client;
} /**
* 值类型 put
*
* @param key
* @param val
* @return
*/
public boolean setObjectVal(String key, Object val) {
try {
redisTemplate.boundValueOps(key).set(val);
return true;
} catch (Exception e) {
return false;
}
} /**
* 值类型put 带过期时间
*
* @param key
* @param val
* @param expries
* @param timeUnit
* @return
*/
public boolean setObjectValExpries(String key, Object val, int expries, TimeUnit timeUnit) {
try {
redisTemplate.boundValueOps(key).set(val, expries, timeUnit);
return true;
} catch (Exception e) {
return false;
}
} /**
* 值类型get
*
* @param key
* @return
*/
public Object getObjectVal(String key) {
try {
return redisTemplate.boundValueOps(key).get();
} catch (Exception e) {
return null;
}
} /**
* set类型put
*
* @param key
* @param val
* @return
*/
public boolean setSetVal(String key, Set val) {
try {
for (Object o : val) {
redisTemplate.boundSetOps(key).add(o);
}
return true;
} catch (Exception e) {
return false;
}
} /**
* set类型get
*
* @param key
* @return
*/
public Set getSetVal(String key) {
try {
return redisTemplate.boundSetOps(key).members();
} catch (Exception e) {
return null;
}
} /**
* 删除set中的一项
*
* @param key
* @param opt
* @return
*/
public boolean removeSetOpt(String key, Object opt) {
try {
redisTemplate.boundSetOps(key).remove(opt);
return true;
} catch (Exception e) {
return false;
}
} public boolean setLeftListVal(String key, List<Object> val) {
try {
for (Object o : val) {
redisTemplate.boundListOps(key).leftPush(o);
}
return true;
} catch (Exception e) {
return false;
}
} public boolean setRightListVal(String key, List<Object> val) {
try {
for (Object o : val) {
redisTemplate.boundListOps(key).rightPush(o);
}
return true;
} catch (Exception e) {
return false;
}
} public List getListVal(String key, int start, int end) {
try {
return redisTemplate.boundListOps(key).range(start, end);
} catch (Exception e) {
return null;
}
} public Object getListVal(String key, int index) {
try {
return redisTemplate.boundListOps(key).index(index);
} catch (Exception e) {
return null;
}
} public boolean removeListOpt(String key, int index, Object opt) {
try {
redisTemplate.boundListOps(key).remove(index, opt);
return true;
} catch (Exception e) {
return false;
}
} //hash类型的不写了 /**
* 删除
*
* @param key
* @return
*/
public boolean delete(String key) {
try {
redisTemplate.delete(key);
return true;
} catch (Exception e) {
return false;
}
}
}

测试

前提:确保配置文件中配置的mysql和redis都正常

因为使用了swagger  可直接运行 访问http://localhost:8080/swagger-ui.html 测试

也可直接访问对应的url http://localhost:8080/user/all

测试redis

package com.blaze.demo;

import com.alibaba.fastjson.JSON;
import com.blaze.demo.model.UserDomain;
import com.blaze.demo.utils.RedisCommon;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource;
import java.util.concurrent.TimeUnit; @RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests { @Resource
private RedisTemplate redisTemplate; @Test
public void blaze() {
RedisCommon redisUtil = new RedisCommon(redisTemplate);
redisUtil.setObjectValExpries("blaze", "123456", 30, TimeUnit.SECONDS);
System.out.println(redisUtil.getObjectVal("blaze")); UserDomain user = new UserDomain();
user.setId(1);
user.setUserId("2333");
user.setUserName("blazeZzz");
redisUtil.setObjectValExpries("blazeZzz", JSON.toJSONString(user), 30, TimeUnit.SECONDS);
System.out.println(redisUtil.getObjectVal("blazeZzz"));
}
}

结果

集成ES

引入依赖

        <dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.0.0</version>
</dependency>

API类

package com.blaze.demo.es;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient; import java.net.InetAddress; /**
* create by zy 2019/6/5 10:52
* TODO 获取client
*/
public class ESClient {
//private EsClient client = new EsClient();
TransportClient client = null; public ESClient() {
try {
client = new PreBuiltTransportClient(Settings.builder().put("cluster.name", "myes").build())
.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.44.81"), 9300))
.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.44.82"), 9300)); } catch (Exception ex) {
client.close();
} finally { }
} public TransportClient getConnection() { if (client == null) {
synchronized (ESClient.class) {
if (client == null) {
new ESClient();
}
}
}
return client; }
}
package com.blaze.demo.es;

import com.alibaba.fastjson.JSON;
import com.blaze.demo.model.UserBaseInfo;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction; import java.util.List; /**
* create by zy 2019/6/5 11:18
* TODO
*/
public class ESUserApi {
ESClient client = new ESClient(); private IndexResponse indexResponse;
private DeleteResponse deleteResponse; public String testInfo() {
List<DiscoveryNode> list = client.getConnection().connectedNodes();
String result = "";
for (DiscoveryNode node : list) {
result += node.getHostAddress() + "|";
}
return result;
} public void index(UserBaseInfo user) {
TransportClient connection = client.getConnection();
indexResponse = connection.prepareIndex("user", "baseinfo")
.setSource(JSON.toJSON(user), XContentType.JSON)
.get();
connection.close();
} /**
* 单个添加
*
* @param user
* @return
*/
public boolean indexOne(UserBaseInfo user) {
TransportClient connection = client.getConnection();
try { indexResponse = connection.prepareIndex("user", "baseinfo")
.setSource(new XContentFactory().jsonBuilder()
.startObject()
.field("id", user.getId())
.field("name", user.getName())
.field("age", user.getAge())
.field("sex", user.getSex())
.field("address", user.getAddress())
.endObject())
.get();
return true;
} catch (Exception e) {
return false;
} finally {
connection.close();
}
} /**
* 批量添加
*
* @param list
* @return
*/
public boolean indexList(List<UserBaseInfo> list) {
TransportClient connection = client.getConnection();
try {
BulkRequestBuilder bulk = client.getConnection().prepareBulk();
for (UserBaseInfo user : list) {
bulk.add(connection.prepareIndex("user", "baseinfo")
.setSource(new XContentFactory().jsonBuilder()
.startObject()
.field("id", user.getId())
.field("name", user.getName())
.field("age", user.getAge())
.field("sex", user.getSex())
.field("address", user.getAddress())
.endObject()));
}
BulkResponse bulkResponse = bulk.get();
return true;
} catch (Exception e) {
return false;
} finally {
connection.close();
}
} /**
* 根据id删除
*
* @param id
* @return
*/
public boolean delById(String id) {
TransportClient connection = client.getConnection();
deleteResponse = connection.prepareDelete("user", "baseinfo", id).get();
return true;
} /**
* 根据userid删除
*
* @param id
* @return
*/
public boolean delete(String id) {
TransportClient connection = client.getConnection();
try {
DeleteByQueryAction.INSTANCE.newRequestBuilder(connection)
.filter(QueryBuilders.matchQuery("id", id))
.source("user")
.execute(new ActionListener<BulkByScrollResponse>() {
public void onResponse(BulkByScrollResponse response) {
long deleted = response.getDeleted();
System.out.println("---------------blaze-----------" + deleted);
} public void onFailure(Exception e) {
System.out.println("---------------blaze delete fail-----------");
}
});
return true;
} catch (Exception e) {
System.out.println("---------------blaze delete error-----------");
return false;
} finally {
connection.close();
}
} /**
* 根据id获取user
* @param id
* @return
*/
public UserBaseInfo queryById(String id) {
TransportClient connection = client.getConnection();
try {
GetResponse response = connection.prepareGet("user", "baseinfo", id).get();
String json = response.getSourceAsString();
UserBaseInfo userBaseInfo = JSON.parseObject(json, UserBaseInfo.class);
return userBaseInfo;
} catch (Exception e) {
return null;
} finally {
connection.close();
}
} }

测试

    @Test
public void testEs() {
UserBaseInfo user = new UserBaseInfo();
user.setAddress("北京");
user.setAge("20");
user.setId("1");
user.setName("张学友");
user.setSex("男");
ESUserApi api = new ESUserApi();
api.indexOne(user);
} @Test
public void esDel() {
ESUserApi api = new ESUserApi();
//String result = api.delById("s6fZJGsBkpzU0bPvXPBt");
//System.out.println(result);
api.delete("1");
}
@Test
public void esQuery(){
ESUserApi api = new ESUserApi();
UserBaseInfo user = api.queryById("23H7JGsBdD3MzWimrdrK");
System.out.println(user.toString());
}

以上。

使用IDEA快速搭建基于Maven的SpringBoot项目(集成使用Redis)的更多相关文章

  1. 用IDEA搭建基于maven的springboot项目

     第一步:新建一个Project 第二步:选择Spring Initializr和SDK 然后next  第三步:修改Group和Artifact 第四步:按自己的需求选,这里我选的是Web,然后ne ...

  2. 基于Maven的SpringBoot项目实现热部署的两种方式

    转载:http://blog.csdn.net/tengxing007/article/details/72675168 前言 JRebel是JavaEE中比较流行的热部署插件,可快速实现热部署,节省 ...

  3. 部署基于maven的springboot项目到linux服务器上

    目录 本地运行调试 导入数据库: 导入项目: 将项目打包: linux准备: 运行项目: 脚本运行 本地运行调试 导入数据库: 导入数据库的时候使用的是sqlYog导入navcat的脚本:由于两个应用 ...

  4. IDEA搭建基于maven的springboot工程

    ---恢复内容开始--- 基础环境:IntelliJ IDEA 2018.1.6 x64.JDK1.8 一.创建maven 填写包名.项目名 选择对应的本地maven 默认过来的project nam ...

  5. 利用Jenkins实现jdk11+Maven构建springboot项目

    目录 原理图 前期准备 Jdk11安装 Jenkins安装 Maven安装 Jenkins的设置 插件安装 变量配置 搭建项目 1.通用配置 2.源码管理 3.构建触发 4.Maven的构建选项 5. ...

  6. 基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建

    基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建 前言 最近做回后台开发,重新抓起以前学过的SSM(Spring+Sp ...

  7. 基于maven的javaweb项目模块化开发

    转自:https://my.oschina.net/kingfire/blog/273381 基于maven的javaweb项目模块化开发 引言 考虑团队拥有多个类似项目的情况,比如一些功能差异不大的 ...

  8. SVN基于Maven的Web项目更新,本地过程详细解释

    周围环境 MyEclipse:10.7 Maven:3.1.1 概要 最近在做项目,MyEclipse下载SVN基于上述Maven的Web问题,有时候搞了非常半天,Maven项目还是出现叉号,最后总结 ...

  9. 工具idea 基于maven 创建springMVC项目

    SpringMVC Spring MVC是Spring提供的一个强大而灵活的web框架.借助于注解,Spring MVC提供了几乎是POJO的开发模式,使得控制器的开发和测试更加简单.这些控制器一般不 ...

随机推荐

  1. 关于PADS的一些概念和实用技巧(二)

    关于PADS的一些概念和实用技巧(二) 声明:引用请注明出处http://blog.csdn.net/lg1259156776/ 1. 关于制作part 首先在logic中绘制CAE封装,在保存元件时 ...

  2. redis key 空闲(一)

    语法: redis 127.0.0.1:6379> COMMAND KEY_NAME 实例: redis 127.0.0.1:6379[1]> select 2 OK redis 127. ...

  3. WebStorm 2018.2安装激活教程

    1.下载解压,得到jetbrains webstorm 2018.2主程序,破解文件和中文语言包: 2.运行“WebStorm-2018.2.exe”开始安装,默认安装目录[C:\Program Fi ...

  4. 教你成为全栈工程师(Full Stack Developer) 四十五-一文读懂hadoop、hbase、hive、spark分布式系统架构

    转载自http://www.shareditor.com/blogshow?blogId=96 机器学习.数据挖掘等各种大数据处理都离不开各种开源分布式系统,hadoop用于分布式存储和map-red ...

  5. poj2185(kmp算法next数组求最小循环节,思维)

    题目链接:https://vjudge.net/problem/POJ-2185 题意:给定由大写字母组成的r×c矩阵,求最小子矩阵使得该子矩阵能组成这个大矩阵,但并不要求小矩阵刚好组成大矩阵,即边界 ...

  6. @ConfigurationProperties和@Value的区别

    @ConfigurationProperties @Value 功能: 批量注入配置文件中的属性 一个个指定,多个属性多个@Value 松散绑定: 支持 不支持 SpEL: 不支持    支持 JSR ...

  7. PAT甲级 二叉树 相关题_C++题解

    二叉树 PAT (Advanced Level) Practice 二叉树 相关题 目录 <算法笔记> 重点摘要 1020 Tree Traversals (25) 1086 Tree T ...

  8. 20191011-构建我们公司自己的自动化接口测试框架-testrun最重要的模块

    testrun模块呢就是最终自动化测试入口,调用前面封装的各个模块主要流程是: 1. 获取测试集种待执行的测试用例 2. 处理测试用例获取的数据,包括转换数据格式,处理数据的中的关联等 3. 处理完数 ...

  9. image analogies笔记

    Image Analogies 个人学习笔记, 根基尚浅, 免不得颇多纰漏, 望批评指教. 这是一篇2001年的文章, 其核心主要讲了如何将一对图片之间的"转换模式"应用到其他图片 ...

  10. ggplot2|theme主题设置,详解绘图优化-“精雕细琢”-

    本文首发于“生信补给站”公众号,https://mp.weixin.qq.com/s/hMjPj18R1cKBt78w8UfhIw 学习了ggplot2的基本绘图元素ggplot2|详解八大基本绘图要 ...