pom.xml

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 因为采用了Redis连接池,所以要引用commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.5.0</version>
</dependency>

application.properties

#
server.address=0.0.0.0
server.port=8080
server.servlet.context-path=/test
server.session.timeout=300
server.error.path=/error
#
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.buffered=true
server.tomcat.accesslog.directory=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/logs
#
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Asia/Shanghai
#
spring.thymeleaf.cache=true
spring.thymeleaf.enabled=true file.upload.path=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/fileUpLoad spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=0
spring.servlet.multipart.location=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/temp
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.resolve-lazily=false spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.one.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.druid.one.username=root
spring.datasource.druid.one.password=gis
spring.datasource.druid.one.driver-class-name=com.mysql.cj.jdbc.Driver ##Druid
spring.datasource.druid.one.initial-size=2
spring.datasource.druid.one.max-active=5
spring.datasource.druid.one.min-idle=1
spring.datasource.druid.one.max-wait=60000
spring.datasource.druid.one.pool-prepared-statements=true
spring.datasource.druid.one.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.one.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.one.validation-query-timeout=60000
spring.datasource.druid.one.test-on-borrow=false
spring.datasource.druid.one.test-on-return=false
spring.datasource.druid.one.test-while-idle=true
spring.datasource.druid.one.time-between-eviction-runs-millis=60000
spring.datasource.druid.one.min-evictable-idle-time-millis=100000
#spring.datasource.druid.one.max-evictable-idle-time-millis=
spring.datasource.druid.one.filters=stat,wall,log
spring.datasource.druid.one.logSlowSql=true #
# debug=true # Enable debug logs.
# trace=true # Enable trace logs. spring.redis.host=127.0.0.1
spring.redis.password=gis
spring.redis.port=6379
spring.redis.pool.max-active=8
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.min-idle=0
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.shutdown-timeout=100ms
spring.redis.ssl=false
spring.redis.timeout=5000 redis.message.topic=spring.news.*

启动类

package com.smartmap.sample.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement; import com.smartmap.sample.test.conf.DataSourceConfiguration; @EnableTransactionManagement
@SpringBootApplication
public class TestRedisApplication { public static void main(String[] args) {
SpringApplication.run(TestRedisApplication.class, args); } }

注册Redis消息监听

package com.smartmap.sample.test.conf;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer; import com.smartmap.sample.test.message.RedisMessageListener; @Configuration
public class RedisChannelListenerConfiguration {
Log log = LogFactory.getLog(RedisChannelListenerConfiguration.class); @Value("${redis.message.topic}")
private String topic; /**
* 注册Redis事件监听
* publish spring.news.user bobobo
*
* @param connectionFactory
* @param listenerAdapter
* @return
*/
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
RedisMessageListener listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic(topic));
log.info("------------> " + topic);
return container;
} @Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
}

Redis消息处理类

package com.smartmap.sample.test.message;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service; @Service
public class RedisMessageListener implements MessageListener {
final Log log = LogFactory.getLog(RedisMessageListener.class); @Autowired
private StringRedisTemplate stringRedisTemplate; public void setRedisTemplate(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
} @Override
public void onMessage(Message message, byte[] pattern) {
byte[] bodyByte = message.getBody();
byte[] channelByte = message.getChannel();
String content = (String) stringRedisTemplate.getValueSerializer().deserialize(bodyByte);
String topic = (String) stringRedisTemplate.getStringSerializer().deserialize(channelByte);
log.info(topic + " " + content);
}
}

Redis配置类

package com.smartmap.sample.test.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; import com.fasterxml.jackson.databind.ObjectMapper; @Configuration
public class RedisConfiguration { @Bean("stringJsonRedisTemplate")
public RedisTemplate<Object, Object> stringJsonRedisTemplate(RedisConnectionFactory redisConnectionFactory,
ObjectMapper mapper) {
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
template.setConnectionFactory(redisConnectionFactory);
template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer(mapper));
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
template.setKeySerializer(stringSerializer);
template.setHashKeySerializer(stringSerializer);
return template;
}
}

JSON转换配置类

package com.smartmap.sample.test.conf;

import java.text.SimpleDateFormat;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import com.fasterxml.jackson.databind.ObjectMapper; @Configuration
public class JacksonConfiguration {
@Bean
public ObjectMapper getObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
return objectMapper;
}
}

实体类 User

package com.smartmap.sample.test.entity;

import java.util.Date;

import com.fasterxml.jackson.annotation.JsonBackReference;

public class User {

    private Long id;

    private String name;

    @JsonBackReference // 防止相互引用,出现无限引用递归
private Department department; private Date createTime; public User() {
} public User(Long id, String name, Department department, Date createTime) {
super();
this.id = id;
this.name = name;
this.department = department;
this.createTime = createTime;
} public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Department getDepartment() {
return department;
} public void setDepartment(Department department) {
this.department = department;
} public Long getDepartmentId() {
return this.department == null ? null : this.department.getId();
} public void setDepartmentId(Long departmentId) {
if (this.department != null) {
this.department.setId(departmentId);
}
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} }

实体类Department

package com.smartmap.sample.test.entity;

import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonManagedReference; public class Department { private Long id; private String name; @JsonManagedReference // 防止相互引用,出现无限引用递归
private Set<User> users = new HashSet<User>(); public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Set<User> getUsers() {
return users;
} public void setUsers(Set<User> users) {
this.users = users;
}
}

DAO类

package com.smartmap.sample.test.dao.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.smartmap.sample.test.dao.UserDao;
import com.smartmap.sample.test.entity.User; @Repository
public class UserDaoImpl implements UserDao {
final Log log = LogFactory.getLog(UserDaoImpl.class); @Autowired
private ObjectMapper objectMapper; @Autowired
@Qualifier("stringJsonRedisTemplate")
private RedisTemplate<Object, Object> redisTemplate; public Long addRootUser(User user) {
String key = "info:root:user";
redisTemplate.opsForValue().set(key, user); Object obj = redisTemplate.opsForValue().get(key);
// 因为返回来的是HashMap对象,需要将其转化为实体对象
User userResult = objectMapper.convertValue(obj, User.class);
// User userResult = (User) redisTemplate.opsForValue().get(key);
if (userResult != null) {
return 1L;
}
return 0L;
} public User getRootUser() {
String key = "info:root:user";
Object obj = redisTemplate.opsForValue().get(key);
// 因为返回来的是HashMap对象,需要将其转化为实体对象
User userResult = objectMapper.convertValue(obj, User.class);
return userResult;
} public Long addUser(User user) {
String key = "info:users";
Long count = redisTemplate.opsForList().leftPush(key, user);
return count;
} public List<User> getUsers() {
String key = "info:users";
List<Object> objectList = (List<Object>) (redisTemplate.opsForList().range(key, 0, -1));
// 因为返回来的是HashMap对象,需要将其转化为实体对象
List<User> userList = new ArrayList<User>();
// 此处用到了Java的Lambda表达式进行转化
objectList.forEach((k) -> {
userList.add(objectMapper.convertValue(k, User.class));
});
return userList;
} public Long removeUser(Long userId) {
String key = "info:users";
User user = (User) redisTemplate.opsForList().leftPop(key);
return user != null ? 1L : 0L;
}

// 调用Redis原始的API来进行操作
public String connectionSet(final String key, final String value) {
Object obj = redisTemplate.execute(new RedisCallback<Object>() { public Object doInRedis(RedisConnection connection) throws DataAccessException {
String message = "fail";
try {
Boolean isSuccess = connection.set(key.getBytes("UTF-8"), value.getBytes("UTF-8"));
if (isSuccess) {
message = "success";
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return message;
}
});
if (obj != null) {
return "success";
} else {
return "fail";
} } }

Service类

package com.smartmap.sample.test.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.smartmap.sample.test.dao.UserDao;
import com.smartmap.sample.test.entity.User;
import com.smartmap.sample.test.service.UserService; @Service
@Transactional
public class UserServiceImpl implements UserService { @Autowired
UserDao userDao; public Long addRootUser(User user) {
return userDao.addRootUser(user);
} public User getRootUser() {
return userDao.getRootUser();
} public Long addUser(User user) {
return userDao.addUser(user);
} public List<User> getAllUsers() {
return userDao.getUsers();
} public Long delete(Long userId) {
return userDao.removeUser(userId);
} public String generateSave(String key, String value) {
return userDao.connectionSet(key, value);
}
}

Controller类

package com.smartmap.sample.test.controller.rest;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.smartmap.sample.test.entity.User;
import com.smartmap.sample.test.service.UserService; @RestController
@RequestMapping("/api/v1.1/system/user")
public class UserRestController {
private final Log logger = LogFactory.getLog(UserRestController.class); @Autowired
UserService userService; /**
* 查询所有用户
*
* curl -XGET 'http://127.0.0.1:8080/test/api/v1.1/system/user/'
*
* @return
*/
@GetMapping("/")
public List<User> getAllUsers() {
return userService.getAllUsers();
} /**
* 添加用户
*
* curl -XPOST 'http://127.0.0.1:8080/test/api/v1.1/system/user/'
* -H'Content-type:application/json;charset=UTF-8' -d ' { "name":"123",
* "createTime":"2017-01-01 00:00:00", "departmentId":"9" }'
*
* @param user
* @return
*/
@PostMapping("/")
public Long addUse(@RequestBody User user) {
System.out.println(user.getName());
return userService.addUser(user);
} /**
* 添加用户
*
* curl -XPOST 'http://127.0.0.1:8080/test/api/v1.1/system/user/root'
* -H'Content-type:application/json;charset=UTF-8' -d ' { "name":"123",
* "createTime":"2017-01-01 00:00:00", "departmentId":"9" }'
*
* @param user
* @return
*/
@PostMapping("/root")
public Long addRootUse(@RequestBody User user) {
System.out.println(user.getName());
return userService.addRootUser(user);
} /**
* 查询所有用户
*
* curl -XGET 'http://127.0.0.1:8080/test/api/v1.1/system/user/root'
*
* @return
*/
@GetMapping("/root")
public User getRootUser() {
return userService.getRootUser();
} /**
* 删除用户
*
* curl -XDELETE 'http://127.0.0.1:8080/test/api/v1.1/system/user/123'
*
* @param userId
* @return
*/
@DeleteMapping("/{userId}")
public String deleteUser(@PathVariable("userId") Long userId) {
Long count = userService.delete(userId);
if (count > 0) {
return "{success:true, message:'delete success'}";
} else {
return "{success:false, message:'delete fail'}";
}
} /**
* 添加用户
*
* curl -XPOST 'http://127.0.0.1:8080/test/api/v1.1/system/user/generate'
* -H'application/x-www-form-urlencoded;charset=UTF-8' -d 'key=key1&value=value1'
*
* @param user
* @return
*/
@PostMapping("/generate")
public String generateSave(@RequestParam("key") String key, @RequestParam("value") String value) {
String result = userService.generateSave(key, value);
return result;
} }

完!

Spring Boot—18Redis的更多相关文章

  1. 玩转spring boot——快速开始

    开发环境: IED环境:Eclipse JDK版本:1.8 maven版本:3.3.9 一.创建一个spring boot的mcv web应用程序 打开Eclipse,新建Maven项目 选择quic ...

  2. 【微框架】之一:从零开始,轻松搞定SpringCloud微框架系列--开山篇(spring boot 小demo)

    Spring顶级框架有众多,那么接下的篇幅,我将重点讲解SpringCloud微框架的实现 Spring 顶级项目,包含众多,我们重点学习一下,SpringCloud项目以及SpringBoot项目 ...

  3. 玩转spring boot——开篇

    很久没写博客了,而这一转眼就是7年.这段时间并不是我没学习东西,而是园友们的技术提高的非常快,这反而让我不知道该写些什么.我做程序已经有十几年之久了,可以说是彻彻底底的“程序老炮”,至于技术怎么样?我 ...

  4. 玩转spring boot——结合redis

    一.准备工作 下载redis的windows版zip包:https://github.com/MSOpenTech/redis/releases 运行redis-server.exe程序 出现黑色窗口 ...

  5. 玩转spring boot——AOP与表单验证

    AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...

  6. 玩转spring boot——结合JPA入门

    参考官方例子:https://spring.io/guides/gs/accessing-data-jpa/ 接着上篇内容 一.小试牛刀 创建maven项目后,修改pom.xml文件 <proj ...

  7. 玩转spring boot——结合JPA事务

    接着上篇 一.准备工作 修改pom.xml文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

  8. 玩转spring boot——结合AngularJs和JDBC

    参考官方例子:http://spring.io/guides/gs/relational-data-access/ 一.项目准备 在建立mysql数据库后新建表“t_order” ; -- ----- ...

  9. 玩转spring boot——结合jQuery和AngularJs

    在上篇的基础上 准备工作: 修改pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

随机推荐

  1. vue 组件之间的数据传递

    父组件传数据给子组件 创建数据 获取json数据 子组件传数据给父组件 1. 子组件使用$emit监听数据 getAreaValues(){ this.$emit('getAreaValues', { ...

  2. 【洛谷mNOIP模拟赛Day1】T1 斐波那契

    题目传送门:https://www.luogu.org/problemnew/show/P3938 这题出得特别吼啊~~ 通过打表或者大胆猜想斐波那契数列的一些性质,我们不难发现对于一只兔子$x$,其 ...

  3. JavaScript 函数的4种调用方法

    JavaScript 函数有 4 种调用方式. 每种方式的不同方式在于 this 的初始化. 作为一个函数调用 function myFunction(a, b) { return a * b; } ...

  4. Java学习之路(十一):IO流<前戏>

    File类的概述和构造方法 构造方法: File(String pathname):根据一个路径得到File对象 File(String parent,String child):根据一个目录和一个子 ...

  5. 数据输入——生成你需要的echart图(世界地图,气泡图)

    上一篇文章介绍了:堆积柱状图.扇形图.嵌套环形图,现在来介绍一下:世界地图和气泡图 1.世界地图 http://echarts.baidu.com/examples/editor.html?c=map ...

  6. Android 开发工具类 31_WebService 获取手机号码归属地

    AndroidInteractWithWebService.xml <?xml version="1.0" encoding="utf-8"?> & ...

  7. Fiddler Web Debugger的下载和安装(图文详解)

    不多说,直接上干货! Fiddler是一个http协议调试代理工具,它能够记录客户端和服务器之间的所有 HTTP请求,可以针对特定的HTTP请求,分析请求数据.设置断点.调试web应用.修改请求的数据 ...

  8. 通用数据库连接池-C3PO

    C3PO是一个开放源代码的JDBC数据连接池实现项目,实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展.开源项目在使用:Hibernate,Spring,MYSQL等. 下载: h ...

  9. python算法之冒泡排序

    目录 python之冒泡排序 算法原理 算法分析 代码实现 总结 python之冒泡排序 概念: 重复地走访过要排序的元素列,依次比较两个相邻的元素,如果他们的顺序(如从大到小.首字母从A到Z)错误就 ...

  10. 再springMVC中自定义文件上传处理解决与原spring中MultipartResolve冲突问题

    相信很多朋友再用springmvc时都遇见了一个问题,那就是自带的获取上传的东西太慢,而且不知道如何修改,其实不然,spring框架既然给我们开放了这个接口,就一定遵从了可扩展性的原则,经过查看org ...