标签:9.png 1.2 启动方式 连接池 端口 rem 连接 pass config
工作需要慢慢替换掉原来的springmvc架构,改用springboot和springcloud一体化全家桶形式,方便以后的多业务微服务、独立程序、分布式搭建做基础。
结合原springmvc 多modules + redis + mq、和springboot资料整理出了全面的一体化项目架构搭建。
1,springboot最明显的优点
(1) 轻便,原先项目里一个工程要一堆配置文件各种xml,properties 等等,现在已经简化并可以放在一个“子工程”下,其他项目只考虑实现业务层。
(2) 省事,以前项目搭建总会考虑很多兼容问题,比如jdk版本和支持包互相版本是否冲突等等。
(3) war,jar已经不是问题了(springboot内置了tomcat),以前web形式项目必定是web格式,现在可以建立jar形式工程。
(4) maven配合可以构建一个很清晰而庞大分工协调的架构。。。。。。
2,非多modules工程搭建
(1) 稳定版本环境 jdk1.7 + maven 3.3.9 也是可行的。
(2) 工具和版本清单:Eclipse Java EE IDE for Web Developers.Build id: 20180405-1200 + maven 3.5.0 + jdk1.8
maven的setting配置:
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<proxies></proxies>
<servers>
<server>
<id>archiva.releases</id>
<username>deployment</username>
<password>deployment</password>
</server>
<server>
<id>archiva.snapshots</id>
<username>deployment</username>
<password>deployment</password>
</server>
<server>
<id>thirdparty</id>
<username>admin</username>
<password>admin123</password>
</server>
</servers>
<!-- 所有对central请求都转向 nexus groups -->
<mirrors>
<mirror>
<!--This sends everything else to /public -->
<id>nexus</id>
<mirrorOf>central</mirrorOf>
<url>http://repo1.maven.org/maven2</url>
</mirror>
</mirrors>
<profiles>
<profile>
<id>central</id>
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>http://repo1.maven.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>snapshots</id>
<name>Snapshots Repository</name>
<url>http://repo1.maven.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>central</id>
<name>Central Repository</name>
<url>http://repo1.maven.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>central</activeProfile>
</activeProfiles>
<localRepository>/Users/yuzhilin/develop/maven_path</localRepository>
</settings>
文件里的localRepository是本地磁盘保存maven下载和项目引用jar包的地方,要记得修改为自己的
##搭建开始##
因为有springboot托管了相关支持包版本控制,只注明spring-boot-starter-parent 为1.5.8.RELEASE 和 mybatis-spring-boot 为1.3.2
eclipse勾选create a simple project 比用在线模版要方便,本地的maven已经提供
工程名叫springboot,打包是以jar形式,后面会讲java -jar xxx.jar或者 java -jar xxx.war启动方式
搭建完成
第一步 配置pom.xml,只引用springboot相关的,mybatis,redis,mq因为单web演示项目就暂时请忽略下,注释见pom.xml
1 <project xmlns="http://maven.apache.org/POM/4.0.0" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 <groupId>org.springboot.study</groupId> 6 <artifactId>springboot</artifactId> 7 <version>0.0.1-SNAPSHOT</version> 8 <!-- 继承说明:这里继承SpringBoot提供的父工程 --> 9 <parent> 10 <groupId>org.springframework.boot</groupId> 11 <artifactId>spring-boot-starter-parent</artifactId> 12 <version>1.5.8.RELEASE</version> 13 <relativePath /> 14 </parent> 15 <dependencies> 16 <!-- SpringBoot Redis --> 17 <dependency> 18 <groupId>org.springframework.boot</groupId> 19 <artifactId>spring-boot-starter-data-redis</artifactId> 20 </dependency> 21 <!-- Springboot 事务 --> 22 <dependency> 23 <groupId>org.springframework.boot</groupId> 24 <artifactId>spring-boot-starter-jdbc</artifactId> 25 </dependency> 26 <dependency> 27 <groupId>org.springframework.boot</groupId> 28 <artifactId>spring-boot-starter-redis</artifactId> 29 <version>1.3.5.RELEASE</version> 30 </dependency> 31 <!-- SpringBoot 缓存 --> 32 <dependency> 33 <groupId>org.springframework.boot</groupId> 34 <artifactId>spring-boot-starter-cache</artifactId> 35 </dependency> 36 <!-- 添加Springboot默认支持的logback作为标准日志输出 --> 37 <dependency> 38 <groupId>org.springframework.boot</groupId> 39 <artifactId>spring-boot-starter-logging</artifactId> 40 </dependency> 41 <dependency> 42 <groupId>org.springframework.boot</groupId> 43 <artifactId>spring-boot-starter-thymeleaf</artifactId> 44 </dependency> 45 <!-- Spring Boot web依赖 --> 46 <dependency> 47 <groupId>org.springframework.boot</groupId> 48 <artifactId>spring-boot-starter-web</artifactId> 49 </dependency> 50 <!-- Spring Boot 热部署 --> 51 <dependency> 52 <groupId>org.springframework.boot</groupId> 53 <artifactId>spring-boot-devtools</artifactId> 54 <optional>true</optional> 55 </dependency> 56 <!-- Spring Boot Mybatis 依赖 --> 57 <dependency> 58 <groupId>org.mybatis.spring.boot</groupId> 59 <artifactId>mybatis-spring-boot-starter</artifactId> 60 <version>1.3.2</version> 61 </dependency> 62 <!-- Spring Boot 相关 --> 63 <dependency> 64 <groupId>org.springframework.boot</groupId> 65 <artifactId>spring-boot-starter-log4j</artifactId> 66 <version>1.3.8.RELEASE</version> 67 </dependency> 68 <dependency> 69 <groupId>org.springframework.boot</groupId> 70 <artifactId>spring-boot-starter-aop</artifactId> 71 </dependency> 72 <dependency> 73 <groupId>org.springframework.boot</groupId> 74 <artifactId>spring-boot-starter-test</artifactId> 75 <scope>test</scope> 76 </dependency> 77 <!-- Springboot,druid 整合包 --> 78 <dependency> 79 <groupId>com.alibaba</groupId> 80 <artifactId>druid-spring-boot-starter</artifactId> 81 <version>1.1.0</version> 82 </dependency> 83 <!-- MySQL 连接驱动依赖 --> 84 <dependency> 85 <groupId>mysql</groupId> 86 <artifactId>mysql-connector-java</artifactId> 87 </dependency> 88 <dependency> 89 <groupId>commons-dbcp</groupId> 90 <artifactId>commons-dbcp</artifactId> 91 </dependency> 92 <!-- json --> 93 <dependency> 94 <groupId>net.sf.json-lib</groupId> 95 <artifactId>json-lib</artifactId> 96 <version>2.4</version> 97 <classifier>jdk15</classifier> 98 </dependency> 99 <dependency> 100 <groupId>com.alibaba</groupId> 101 <artifactId>fastjson</artifactId> 102 <version>1.2.41</version> 103 </dependency> 104 <!-- commons --> 105 <dependency> 106 <groupId>org.apache.commons</groupId> 107 <artifactId>commons-lang3</artifactId> 108 <version>3.3.2</version> 109 </dependency> 110 <!-- httpClient --> 111 <dependency> 112 <groupId>org.apache.httpcomponents</groupId> 113 <artifactId>httpclient</artifactId> 114 </dependency> 115 <!-- aliYun start --> 116 <dependency> 117 <groupId>redis.clients</groupId> 118 <artifactId>jedis</artifactId> 119 <type>jar</type> 120 <scope>compile</scope> 121 </dependency> 122 <dependency> 123 <groupId>org.apache.commons</groupId> 124 <artifactId>commons-pool2</artifactId> 125 </dependency> 126 <!-- <dependency> <groupId>com.alipay.java.sdk</groupId> <artifactId>alipay-sdk</artifactId> 127 <version>1.0.0</version> </dependency> <dependency> <groupId>com.alipay</groupId> 128 <artifactId>alipay-sdk-java</artifactId> <version>20170615110434</version> 129 </dependency> --> 130 <dependency> 131 <groupId>com.aliyun</groupId> 132 <artifactId>aliyun-java-sdk-core</artifactId> 133 <version>3.3.1</version> 134 </dependency> 135 <dependency> 136 <groupId>com.aliyun</groupId> 137 <artifactId>aliyun-java-sdk-dysmsapi</artifactId> 138 <version>1.0.0</version> 139 </dependency> 140 <!-- aliYun end --> 141 <!-- aliMq --> 142 <dependency> 143 <groupId>com.aliyun.openservices</groupId> 144 <artifactId>ons-client</artifactId> 145 <version>1.6.0.Final</version> 146 </dependency> 147 <!-- Spring Aop --> 148 <dependency> 149 <groupId>org.aspectj</groupId> 150 <artifactId>aspectjweaver</artifactId> 151 </dependency> 152 <dependency> 153 <groupId>org.springframework</groupId> 154 <artifactId>spring-beans</artifactId> 155 </dependency> 156 <dependency> 157 <groupId>org.springframework</groupId> 158 <artifactId>spring-context</artifactId> 159 </dependency> 160 <dependency> 161 <groupId>org.springframework</groupId> 162 <artifactId>spring-context-support</artifactId> 163 </dependency> 164 <dependency> 165 <groupId>org.springframework</groupId> 166 <artifactId>spring-core</artifactId> 167 </dependency> 168 <dependency> 169 <groupId>org.springframework</groupId> 170 <artifactId>spring-jdbc</artifactId> 171 </dependency> 172 <dependency> 173 <groupId>org.springframework</groupId> 174 <artifactId>spring-webmvc</artifactId> 175 </dependency> 176 <!-- Spring end --> 177 </dependencies> 178 </project>
第二步 新建application.properties
application.properties
spring.profiles.active=dev ## 数据库连接 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/yugh?useUnicode=true&characterEncoding=UTF-8&socketTimeout=50000&connectTimeout=20000&zeroDateTimeBehavior=convertToNull&useSSL=false spring.datasource.username=root spring.datasource.password=mysqlroot ## 可以用java -jar --server.port=XX 启动指定端口号 server.port=8070 ## 数据库连接池 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.druid.initial-size=5 spring.datasource.druid.min-idle=5 spring.datasource.druid.max-active=20 spring.datasource.druid.max-wait=60000 spring.datasource.druid.time-between-eviction-runs-millis=60000 spring.datasource.druid.min-evictable-idle-time-millis=300000 spring.datasource.druid.validation-query=SELECT 1 FROM DUAL spring.datasource.druid.test-while-idle=true spring.datasource.druid.test-on-borrow=false spring.datasource.druid.test-on-return=false pring.datasource.druid.pool-prepared-statements=true spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20 spring.datasource.druid.filters=stat,wall,log4j ## mybatis配置 mybatis.config-location=classpath:mybatis/mybatis-config.xml mybatis.mapper-locations=classpath:mybatis/mapper/*.xml mybatis.type-aliases-package = org.springboot.model ## redis # Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=localhost # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 # 连接池中的最大空闲连接 spring.redis.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=0 #aliyun MQ config accessKey=XX secretKey=XX tag=XX topic=XX
1:第一行开发模式,单module,默认或注释#掉
2:数据库配置、端口号指定
3:连接池配置采用druid
4:mybatis配置和redis配置
第三步 创建出现在application.properties中的mybatis配置
1:在src/main/resources下新建一个package,名字mybatis,粘贴以下配置
mybatis-config.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 默认全部开启 add by yugh-->
<!-- 获取数据库自增主键值 -->
<setting name="useGeneratedKeys" value="true"/>
<!-- 使用列别名替换列名,默认为 true -->
<setting name="useColumnLabel" value="true"/>
<!-- 开启驼峰命名 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 打印sql语句 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
</configuration>
2:mapper和model对象用mybatis的反向生成
https://files.cnblogs.com/files/KuJo/MybatisGenerator.zip
下载我提供的文件夹,解压后,修改配置文件里的数据库配置和反向表,阅读readme.txt,用命令生成
3:创建package名字为org.springboot.dao,把反向生成的mapper粘贴进去,为了测试我再加了一个方法在UserMapper.java里
package org.springboot.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.springboot.model.User;
import org.springframework.transaction.annotation.Transactional;
@Mapper
public interface UserMapper {
int deleteByPrimaryKey(Long id);
@Transactional
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
@Transactional
List<User> getUserList();
}
为了项目的可维护性,我采用的还是*Mapper.xml形式, @Mapper注解只是告知springboot在启动后扫描到此包下,和以前的xml配置同理
4:在 1 方法中的mybatis包下新建一个Folder,名叫mapper,新建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="org.springboot.dao.UserMapper">
<resultMap id="BaseResultMap" type="org.springboot.model.User">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="ad_id" jdbcType="INTEGER" property="adId" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
</resultMap>
<sql id="Base_Column_List">
id, name, password, ad_id, create_time
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from ka_ad_login
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from ka_ad_login
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="org.springboot.model.User">
insert into ka_ad_login (id, name, password,
ad_id, create_time)
values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{adId,jdbcType=INTEGER},now())
</insert>
<insert id="insertSelective" parameterType="org.springboot.model.User">
insert into ka_ad_login
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="password != null">
password,
</if>
<if test="adId != null">
ad_id,
</if>
<if test="createTime != null">
create_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=BIGINT},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="adId != null">
#{adId,jdbcType=INTEGER},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="org.springboot.model.User">
update ka_ad_login
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="adId != null">
ad_id = #{adId,jdbcType=INTEGER},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="org.springboot.model.User">
update ka_ad_login
set name = #{name,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
ad_id = #{adId,jdbcType=INTEGER},
create_time = #{createTime,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=BIGINT}
</update>
<select id="getUserList" resultMap="BaseResultMap">
select * from ka_ad_login
</select>
</mapper>
项目文件夹和配置文件结构应该是这样的:
第四步 编写service层
1:创建package名字为org.springboot.service,取消service接口和实现,直接UserService.java
package org.springboot.service;
import java.util.List;
import org.springboot.dao.UserMapper;
import org.springboot.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
/**
* 取消了service实现
*/
private String keyList = "userList";
@Autowired
UserMapper userMapper;
//@Autowired
//RedisUtils redis;
//测试用,在controller里先插入,后获取并set到redis里
public List<User> getUserList() {
//redis.set("userList", keyList);
List<User> userList = userMapper.getUserList();
//redis.set(keyList, JSONArray.fromObject(userList));
//System.out.println(redis.get("userList"));
//redis.remove("userList");
return userList;
}
//测试用,在controller里先插入
public int insertUser(User user) {
int add = userMapper.insert(user);
return add;
}
}
先编写service和controller后最后添加redis
3:创建package名字为org.springboot.controller,名字UserController.java
package org.springboot.controller;
import java.util.List;
import org.springboot.model.User;
import org.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author: YuGenHai
* @name: UserController.java
* @creation: 2018年5月31日 上午9:48:04
* @notes: 测试
*/
@RestController
@RequestMapping(value = "/users")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
public List<User> getUserList(@RequestParam(value = "name", required = false)String name,
@RequestParam(value = "pasword", required = false) String pasword, @RequestParam(value = "adid", required = false) Integer adid) {
User user = new User();
user.setAdId(adid);
user.setName(name);
user.setPassword(pasword);
int add = userService.insertUser(user);
System.out.println(add);
return userService.getUserList();
}
}
@RestController 等于@Controller和@ResponseBody注解
第五步 在src/main/java下新建一个Application.java
注释:在写测试包没有注意提前规划分包类,导致现在不好重新删掉重建,主要目的是让Application.java在其他包或者类的最外层,在springboot启动注解后利于扫描用到的注解
解决办法:找到项目里会看的和org包并排的Application.java,拖到文件夹org.springboot下,和controller,dao,model,service并排
1:现在是这样的:
2:Application.java
package org.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@SpringBootApplication等于@Configuration,@EnableAutoConfiguration,@ComponentScan,直接在最外层添加此注解@SpringBootApplication扫描整个项目所有注解
3:运行方式,直接右键Run As --> Java Application 和 Springboot App原理是一样的,除非在dev test prod分工模式下会去run config下environment下添加工作模式。。。
4:用postman测试下
数据正常入库和返回
第六步 安装redis并启动,安装Redis Desktop Manager
1:在org.springboot包下,新建org.springboot.redis
创建RedisUtils.java
package org.springboot.redis;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
/**
* @author: YuGenHai
* @name: RedisUtils.java
* @creation: 2018年5月31日 下午5:50:51
* @notes: Spring Boot Redis
*/
@Component
@SuppressWarnings({"rawtypes","unchecked"})
public class RedisUtils {
private static final Logger logger = LoggerFactory.getLogger(RedisUtils.class);
@Autowired
private RedisTemplate redisTemplate;
static {
logger.info("redis 开始使用....... ");
}
/**
* 写入缓存
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存设置时效时间
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 批量删除对应的value
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 删除对应的value
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 哈希 添加
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
}
/**
* 哈希获取数据
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}
/**
* 列表添加
* @param k
* @param v
*/
public void lPush(String k, Object v) {
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k, v);
}
/**
* 列表获取
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> lRange(String k, long l, long l1) {
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k, l, l1);
}
/**
* 集合添加
* @param key
* @param value
*/
public void add(String key, Object value) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key, value);
}
/**
* 集合获取
* @param key
* @return
*/
public Set<Object> setMembers(String key) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* 有序集合添加
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key, Object value, double scoure) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key, value, scoure);
}
/**
* 有序集合获取
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
}
创建RedisCacheConfig.java
package org.springboot.redis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author: YuGenHai
* @name: RedisCacheConfig.java
* @creation: 2018年5月31日 下午5:50:15
* @notes: Redis缓存设置
*/
@Configuration
@EnableCaching
public class RedisCacheConfig {
private static final Logger logger = LoggerFactory.getLogger(RedisCacheConfig.class);
@Bean
public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
CacheManager cacheManager = new RedisCacheManager(redisTemplate);
return cacheManager;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
redisTemplate.setConnectionFactory(factory);
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(redisSerializer);
redisTemplate.setHashKeySerializer(redisSerializer);
logger.info("redis 缓存运行..... " + redisTemplate.getStringSerializer());
return redisTemplate;
}
}
2:解开UserService.java的redis注释
package org.springboot.service;
import java.util.List;
import org.springboot.dao.UserMapper;
import org.springboot.model.User;
import org.springboot.redis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import net.sf.json.JSONArray;
@Service
public class UserService {
/**
* 取消了service实现
*/
private String keyList = "userList";
@Autowired
UserMapper userMapper;
@Autowired
RedisUtils redis;
//测试用,在controller里先插入,后获取并set到redis里
public List<User> getUserList() {
List<User> userList = userMapper.getUserList();
redis.set(keyList, JSONArray.fromObject(userList));
System.out.println(redis.get("userList"));
//redis.remove("userList");
return userList;
}
//测试用,在controller里先插入
public int insertUser(User user) {
int add = userMapper.insert(user);
return add;
}
}
3:重新启动Appliaction
再用postman提交一次数据
##搭建结束##
3,MQ队列搭建需要MQ工程来配合,写在随笔里特别多,完整SpringBoot全套资源请访问我的github连接
https://github.com/yugenhai108/SpringBoot_Modules
SpringBoot + Mybatis整合多modules搭建整合Redis+MQ
标签:9.png 1.2 启动方式 连接池 端口 rem 连接 pass config
原文地址:https://www.cnblogs.com/KuJo/p/9125818.html