本博客仅供参考,本人实现没有问题。

1、环境

  先安装redis、mysql

2、springboot2.0的项目搭建(请自行完成),本人是maven项目,因此只需配置,获取相应的jar包,配置贴出。

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!--配置mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <!--配置数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency> <!-- 配置redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.3.RELEASE</version>
</dependency> <!-- 配置fastjson,用于redis转换-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
</dependencies>

  

3、如果相应的springboot可以正常启动,同时mysql和redis已安装,相应的数据库配置如下(#本人使用了mysql做数据库,redis做缓存和消息队列)。

#默认使用配置
spring:
profiles:
active: dev #公共配置与profiles选择无关
mybatis:
typeAliasesPackage: com.cn.commodity.entity
mapperLocations: classpath:mapper/*.xml --- #开发配置
spring:
profiles: dev datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username: root
password: yang156122
driver-class-name: com.mysql.jdbc.Driver
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource #redis配置
redis:
host: 127.0.0.1
port: 6379
password:
pool:
max-active: 100
max-idle: 10
max-wait: 100000
timeout: 0

 

4、mysql数据库表如下图所示:

 

到此,环境和数据库都已准备。项目代码如下:

controller层

  1、UserController

import com.alibaba.fastjson.JSONObject;
import com.cn.commodity.entity.User;
import com.cn.commodity.service.RedisService;
import com.cn.commodity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List; @Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService; @Autowired
private RedisService redisService; private JSONObject json = new JSONObject(); @RequestMapping("/showUser")
@ResponseBody
public User showUser(HttpServletRequest request){
User user = null;
int userId = Integer.parseInt(request.getParameter("id"));
String result = redisService.get("user");
if(result==null) {
user = this.userService.getUserById(userId);
System.out.println("来自数据库:"+user.getUserName());
redisService.set("user",json.toJSONString(user));
}else {
user = json.parseObject(result, User.class);
System.out.println("来自redis缓存:"+user.getUserName());
}
return user;
} @RequestMapping("/showListUser")
@ResponseBody
public List<User> showListUser(HttpServletRequest request) {
List<User> userList = null;
String result = redisService.get("userList");
if(result==null){
userList = userService.selectAllUser();
System.out.println("来自数据库:"+userList);
redisService.set("userList",json.toJSONString(userList));
}else {
userList = json.parseArray(result, User.class);
System.out.println("来自redis缓存:"+userList);
}
System.out.println(userList);
return userList;
}
}

  2、PublisherController.java

import com.cn.commodity.service.PublisherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List; @RestController
@RequestMapping("publisher")
public class PublisherController { @Autowired
private PublisherService publisherService; @RequestMapping("{name}")
public String sendMessage(@PathVariable("name") String name) {
List<String> strLists = new ArrayList<>();
for(int i =0 ;i<10;i++){
String result = publisherService.sendMessage(name+i);
strLists.add(result);
}
return strLists.toString();
}
}

config层

  1、RedisConfig.java

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig; @Configuration
@EnableAutoConfiguration
public class RedisConfig { @Bean
@ConfigurationProperties(prefix = "spring.redis.pool")
public JedisPoolConfig getRedisConfig(){
JedisPoolConfig config = new JedisPoolConfig();
return config;
} @Bean
@ConfigurationProperties(prefix = "spring.redis")
public JedisConnectionFactory getConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setUsePool(true);
JedisPoolConfig config = getRedisConfig();
factory.setPoolConfig(config);
return factory;
} @Bean
public RedisTemplate<?, ?> getRedisTemplate() {
JedisConnectionFactory factory = getConnectionFactory();
RedisTemplate<?, ?> template = new StringRedisTemplate(factory);
return template;
} }

  2、SubscriberConfig.java

import com.cn.commodity.entity.Receiver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; @Configuration
@AutoConfigureAfter({Receiver.class})
public class SubscriberConfig { /**
* 消息监听适配器,注入接受消息方法,输入方法名字 反射方法
*
* @param receiver
* @return
*/
@Bean
public MessageListenerAdapter getMessageListenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage"); //当没有继承MessageListener时需要写方法名字
} /**
* 创建消息监听容器
*
* @param redisConnectionFactory
* @param messageListenerAdapter
* @return
*/
@Bean
public RedisMessageListenerContainer getRedisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory, MessageListenerAdapter messageListenerAdapter) {
RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
redisMessageListenerContainer.addMessageListener(messageListenerAdapter, new PatternTopic("TOPIC_USERNAME"));
return redisMessageListenerContainer;
}
}

3、Dao层

  1、UserDao.java

import com.cn.commodity.entity.User;

import java.util.List;

public interface UserDao {
int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); List<User> selectAllUser();
}

4、entity层

  1、Receiver.java

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component; @Component
public class Receiver implements MessageListener {
private static Logger logger = LoggerFactory.getLogger(Receiver.class); @Autowired
private StringRedisTemplate redisTemplate; @Override
public void onMessage(Message message, byte[] pattern) {
RedisSerializer<String> valueSerializer = redisTemplate.getStringSerializer();
String deserialize = valueSerializer.deserialize(message.getBody());
logger.info("收到的mq消息" + deserialize);
}
}

  2、User.java

public class User {
private Integer id; private String userName; private String password; private Integer age; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password == null ? null : password.trim();
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}

5、Service层

  1、UserService.java

import com.cn.commodity.entity.User;

import java.util.List;

public interface UserService {
/**
* 通过id查找用户
* @param userId
* @return
*/
public User getUserById(int userId); /**
* 添加用户
* @param record
* @return
*/
boolean addUser(User record); /**
* 查询所有用户
* @return
*/
List<User> selectAllUser(); }

  2、RedisService.java

public interface RedisService {

    /**
* set存数据
* @param key
* @param value
* @return
*/
boolean set(String key, String value); /**
* get获取数据
* @param key
* @return
*/
String get(String key); /**
* 设置有效天数
* @param key
* @param expire
* @return
*/
boolean expire(String key, long expire); /**
* 移除数据
* @param key
* @return
*/
boolean remove(String key); }

  3、PublisherService .java

public interface PublisherService {

     String sendMessage(String name);
}

6、ServiceImp实现层

  1、UserServiceImpl.java

import com.cn.commodity.dao.UserDao;
import com.cn.commodity.entity.User;
import com.cn.commodity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import javax.annotation.Resource;
import java.util.List;
import java.util.Map; @Service("userService")
public class UserServiceImpl implements UserService { @Resource
private UserDao userDao; @Override
public User getUserById(int userId) {
return userDao.selectByPrimaryKey(userId);
}
@Override
public boolean addUser(User record){
boolean result = false;
try {
userDao.insertSelective(record);
result = true;
} catch (Exception e) {
e.printStackTrace();
} return result;
} @Override
public List<User> selectAllUser() {
return userDao.selectAllUser();
} }

  2、RedisServiceImpl.java

import com.cn.commodity.service.RedisService;
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.serializer.RedisSerializer;
import org.springframework.stereotype.Service; import javax.annotation.Resource;
import java.util.concurrent.TimeUnit; @Service("redisService")
public class RedisServiceImpl implements RedisService { @Resource
private RedisTemplate<String, ?> redisTemplate; @Override
public boolean set(final String key, final String value) {
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
connection.set(serializer.serialize(key), serializer.serialize(value));
return true;
}
});
return result;
} @Override
public String get(final String key) {
String result = redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
byte[] value = connection.get(serializer.serialize(key));
return serializer.deserialize(value);
}
});
return result;
} @Override
public boolean expire(final String key, long expire) {
return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
} @Override
public boolean remove(final String key) {
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
connection.del(key.getBytes());
return true;
}
});
return result;
}
}

  3、PublisherServiceImpl.java

import com.cn.commodity.service.PublisherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service; @Service("publisherService")
public class PublisherServiceImpl implements PublisherService {
private static final Logger log = LoggerFactory.getLogger(PublisherServiceImpl.class);
@Autowired
private StringRedisTemplate redisTemplate; @Override
public String sendMessage(String name) {
try {
redisTemplate.convertAndSend("TOPIC_USERNAME", name);
return "消息发送成功了"; } catch (Exception e) {
e.printStackTrace();
return "消息发送失败了";
}
} }

  

7、UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.cn.commodity.dao.UserDao" >
<resultMap id="BaseResultMap" type="com.cn.commodity.entity.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, user_name, password, age
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from user_t
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from user_t
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.cn.commodity.entity.User" >
insert into user_t (id, user_name, password,
age)
values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="com.cn.commodity.entity.User" >
insert into user_t
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="userName != null" >
user_name,
</if>
<if test="password != null" >
password,
</if>
<if test="age != null" >
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="userName != null" >
#{userName,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
<if test="age != null" >
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.cn.commodity.entity.User" >
update user_t
<set >
<if test="userName != null" >
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="password != null" >
password = #{password,jdbcType=VARCHAR},
</if>
<if test="age != null" >
age = #{age,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.cn.commodity.entity.User" >
update user_t
set user_name = #{userName,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update> <select id="selectAllUser" resultMap="BaseResultMap" >
select
<include refid="Base_Column_List" />
from user_t
</select> </mapper>

8、主程序CommodityApplication

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @MapperScan("com.cn.commodity.dao")
@SpringBootApplication
public class CommodityApplication extends SpringBootServletInitializer { public static void main(String[] args) {
SpringApplication.run(CommodityApplication.class, args);
}
}

注意:@MapperScan("com.cn.commodity.*")是错误的,必要要到dao包,即@MapperScan("com.cn.commodity.dao"),本人在开发过程就犯了这个错误,找了很久。

到此,所有代码都已贴上,准确无误。

开始运行:

1、启动redis:

  redis-server.exe redis.windows.conf #服务端

  redis-cli.exe  #客服端

2、执行

  http://localhost:8080/publisher/杨123   #这个是现实消息队列

  http://localhost:8080/user/showUser?id=1  #这个是实现redis做缓存

 

springboot2.0+redis实现消息队列+redis做缓存+mysql的更多相关文章

  1. Redis除了做缓存--Redis做消息队列/Redis做分布式锁/Redis做接口限流

    1.用Redis实现消息队列 用命令lpush入队,rpop出队 Long size = jedis.lpush("QueueName", message);//返回存放的数据条数 ...

  2. PHP使用Redis实现消息队列

    消息队列可以使用MySQL来实现,可以参考博客PHP使用MySQL实现消息队列,虽然用MySQL可以实现,但是一般不这么用,因为MySQL的数据都存在硬盘中,而从硬盘中对MySQL的操作,I/O花费的 ...

  3. redis实现消息队列&发布/订阅模式使用

    在项目中用到了redis作为缓存,再学习了ActiveMq之后想着用redis实现简单的消息队列,下面做记录.   Redis的列表类型键可以用来实现队列,并且支持阻塞式读取,可以很容易的实现一个高性 ...

  4. sping+redis实现消息队列的乱码问题

    使用spring支持redis实现消息队列,参考官方样例:https://spring.io/guides/gs/messaging-redis/ 实现后在运行过程中发现消费者在接收消息时会出现乱码的 ...

  5. Redis作为消息队列服务场景应用案例

    NoSQL初探之人人都爱Redis:(3)使用Redis作为消息队列服务场景应用案例   一.消息队列场景简介 “消息”是在两台计算机间传送的数据单位.消息可以非常简单,例如只包含文本字符串:也可以更 ...

  6. redis resque消息队列

    Resque 目前正在学习使用resque .resque-scheduler来发布异步任务和定时任务,为了方便以后查阅,所以记录一下. resque和resque-scheduler其优点在于功能比 ...

  7. 【Redis】php+redis实现消息队列

    在项目中使用消息队列一般是有如下几个原因: 把瞬间服务器的请求处理换成异步处理,缓解服务器的压力 实现数据顺序排列获取 redis实现消息队列步骤如下: 1).redis函数rpush,lpop 2) ...

  8. Lumen开发:结合Redis实现消息队列(1)

    1.简介 Lumen队列服务为各种不同的后台队列提供了统一的API.队列允许你推迟耗时任务(例如发送邮件)的执行,从而大幅提高web请求速度. 1.1 配置 .env文件的QUEUE_DRIVER选项 ...

  9. 【springboot】【redis】springboot+redis实现发布订阅功能,实现redis的消息队列的功能

    springboot+redis实现发布订阅功能,实现redis的消息队列的功能 参考:https://www.cnblogs.com/cx987514451/p/9529611.html 思考一个问 ...

随机推荐

  1. 【6】Zookeeper脚本及API

    一.客户端脚本 1.1.客户端连接 cd /usr/local/services/zookeeper/zookeeper-3.4.13/bin ##连接本地Zookeeper服务器 sh zkCli. ...

  2. WebLogic 12c Linux 命令行 静默安装

    CentOS 6.3安装配置Weblogic 10  http://www.linuxidc.com/Linux/2014-02/96918.htm Oracle WebLogic 11g 安装部署文 ...

  3. mysql tinyint(1) 在java中被转化为boolean

    数据库表字段类型为:tinyint 长度为1 在java中对应的类型是boolean 查询时直接在页面展示成true或false 如果是2,3,4 这样的也是默认成true,非常不友好. 解决方案: ...

  4. 实时跟踪之TRACA

    背景: 目前,在实时跟踪领域存在着越来越多的先进方法,同时也极大地促进了该领域的发展.主要有两种不同的基于深度学习的跟踪方法:1.由在线跟踪器组成,这些跟踪器依赖网络连续的微调来学习目标的变化外观,精 ...

  5. Django_02_创建模型

    一:ORM简介 ORM,全拼Object-Relation Mapping,中文意为对象-关系映射,是随着面向对象的软件开发方法发展而产生的. 面向对象的开发方法是当今企业级应用开发环境中的主流开发方 ...

  6. Linux系统上对其他用户隐藏进程的简单方法

    mount -o remount,rw,hidepid=2 /proc 我使用的是多用户系统,大部分的用户通过ssh客户端访问他们的资源.我如何(怎么样)避免泄露进程信息给他们?如何(怎么样)在Deb ...

  7. django国际化的简单设置

    设置国际化的具体步骤: 一.国际化 1)效果:针对不同的国家的人可以配置不同的语言(一般是英文和中文,  English  Chinese) 2)目的:增加项目的用户量 3)难度:不难 比较费劲的就是 ...

  8. CSS基础学习 16.CSS过渡

  9. Python JSONⅢ

    JSON 函数 encode Python encode() 函数用于将 Python 对象编码成 JSON 字符串. 语法 实例 以下实例将数组编码为 JSON 格式数据: 以上代码执行结果为: d ...

  10. maven工程指定jdk版本,maven全局配置jdk的版本