使用IDEA快速搭建基于Maven的SpringBoot项目(集成使用Redis)
迫于好久没写博客心慌慌,随便写个简单版的笔记便于查阅。
新建项目
新建项目 然后起名 继续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()); }
以上。