- @date: 2019/10/3 11:45
*/
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000);
factory.setReadTimeout(5000);
return factory;
}
}
- 接下来是提供web服务的controller:
package com.bolingcavalry.servicea.controller;
import com.alibaba.fastjson.JSON;
import com.bolingcavalry.servicea.entity.Student;
import com.bolingcavalry.servicea.mapper.StudentMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
-
@Description: 提供学生服务相关的web接口
-
@author: willzhao E-mail: zq2599@gmail.com
-
@date: 2019/10/3 8:51
*/
@RestController
public class StudentController {
@Autowired
StudentMapper studentMapper;
@Autowired
private RestTemplate restTemplate;
@Value(“${serviceb.baseurl}”)
private String baseUrl;
@RequestMapping(value = “/get/{id}”, method = RequestMethod.GET)
public String get(@PathVariable(“id”) Integer id) {
String rlt = restTemplate.getForObject(baseUrl + “get/” + id,String.class);
if(StringUtils.isNotBlank(rlt)){
return “From redis :” + rlt;
}
//redis中查不到,就去数据库里面查
Student student = studentMapper.getById(id);
//mysql里面也没有就报错
if(null==student) {
return “student with id[”+id+“] not exist”;
}
//调用service-b的接口,写入redis
restTemplate.getForObject(baseUrl + “set/”+id+“/”+student.getName(),String.class);
return “From mysql :”+JSON.toJSONString(student);
}
@RequestMapping(value = “/add/{id}/{name}”, method = RequestMethod.GET)
public String add(@PathVariable(“id”) Integer id, @PathVariable(“name”) String name) {
Student student = new Student();
student.setId(id);
student.setName(name);
//写入数据库
studentMapper.insert(student);
//调用service-b的接口,写入redis
restTemplate.getForObject(baseUrl + “set/”+id+“/”+name,String.class);
return “insert success”;
}
}
- 整个应用的启动类,增加了MapperScan注解:
package com.bolingcavalry.servicea;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(“com.bolingcavalry.servicea.mapper”)
public class ServiceAApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceAApplication.class, args);
}
}
以上就是service-a的全部源码了,包括mybatis和restTmeplate操作;
service-b源码
- 创建名为service-b的子工程,pom.xml如下,要注意的是依赖了spring-boot-starter-data-redis和commons-pool2:
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd”>
4.0.0
com.bolingcavalry
pinpoint185demo
1.0-SNAPSHOT
service-b
service-b
服务b
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-starter-web
com.alibaba
fastjson
1.2.28
org.apache.commons
commons-pool2
2.0
org.springframework.boot
spring-boot-maven-plugin
- 应用的配置文件application.properties内容如下:
server.port=8081
#redis
spring.redis.host=192.168.121.144
spring.redis.port=6379
数据库连接超时时间,2.0 中该参数的类型为Duration,这里在配置的时候需要指明单位
spring.redis.timeout=60s
连接池配置,2.0中直接使用jedis或者lettuce配置连接池
最大活跃连接数,负数为不限制
spring.redis.lettuce.pool.max-active=50
等待可用连接的最大时间,负数为不限制
spring.redis.lettuce.pool.max-wait=-1ms
最大空闲连接数
spring.redis.lettuce.pool.max-idle=10
最小空闲连接数
spring.redis.lettuce.pool.min-idle=2
- redis的配置类:
package com.example.serviceb.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
-
@Description: (这里用一句话描述这个类的作用)
-
@author: willzhao E-mail: zq2599@gmail.com
-
@date: 2019/10/3 11:06
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
-
retemplate相关配置
-
@param factory
-
@return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
/**
-
对hash类型的数据操作
-
@param redisTemplate
-
@return
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
-
对redis字符串类型数据操作
-
@param redisTemplate
-
@return
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
-
对链表类型的数据操作
-
@param redisTemplate
-
@return
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
-
对无序集合类型的数据操作
-
@param redisTemplate
-
@return
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
-
对有序集合类型的数据操作
-
@param redisTemplate
-
@return
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
- redis的工具类:
package com.example.serviceb.util;
/**
-
@Description: (这里用一句话描述这个类的作用)
-
@author: willzhao E-mail: zq2599@gmail.com
-
@date: 2019/10/3 11:09
*/
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
- redisTemplate封装
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
-
指定缓存失效时间
-
@param key 键
-
@param time 时间(秒)
-
@return
*/
public boolean expire(String key,long time){
try {
if(time>0){
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
-
根据key 获取过期时间
-
@param key 键 不能为null
-
@return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
/**
-
判断key是否存在
-
@param key 键
-
@return true 存在 false不存在
*/
public boolean hasKey(String key){
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
-
删除缓存
-
@param key 可以传一个值 或多个
*/
@SuppressWarnings(“unchecked”)
public void del(String … key){
if(key!=null&&key.length>0){
if(key.length==1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
//String=
/**
-
普通缓存获取
-
@param key 键
-
@return 值
*/
public Object get(String key){
return key==null?null:redisTemplate.opsForValue().get(key);
}
/**
-
普通缓存放入
-
@param key 键
-
@param value 值
-
@return true成功 false失败
*/
public boolean set(String key,Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
-
普通缓存放入并设置时间
-
@param key 键
-
@param value 值
-
@param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
-
@return true成功 false 失败
*/
public boolean set(String key,Object value,long time){
try {
if(time>0){
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}else{
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
-
递增
-
@param key 键
-
@param delta 要增加几(大于0)
-
@return
*/
public long incr(String key, long delta){
if(delta<0){
throw new RuntimeException(“递增因子必须大于0”);
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
-
递减
-
@param key 键
-
@param delta 要减少几(小于0)
-
@return
*/
public long decr(String key, long delta){
if(delta<0){
throw new RuntimeException(“递减因子必须大于0”);
}
return redisTemplate.opsForValue().increment(key, -delta);
}
//Map=
/**
-
HashGet
-
@param key 键 不能为null
-
@param item 项 不能为null
-
@return 值
*/
public Object hget(String key,String item){
return redisTemplate.opsForHash().get(key, item);
}
/**
-
获取hashKey对应的所有键值
-
@param key 键
-
@return 对应的多个键值
*/
public Map<Object,Object> hmget(String key){
return redisTemplate.opsForHash().entries(key);
}
/**
-
HashSet
-
@param key 键
-
@param map 对应多个键值
-
@return true 成功 false 失败
*/
public boolean hmset(String key, Map<String,Object> map){
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
-
HashSet 并设置时间
-
@param key 键
-
@param map 对应多个键值
-
@param time 时间(秒)
-
@return true成功 false失败
*/
public boolean hmset(String key, Map<String,Object> map, long time){
try {
redisTemplate.opsForHash().putAll(key, map);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
-
向一张hash表中放入数据,如果不存在将创建
-
@param key 键
-
@param item 项
-
@param value 值
-
@return true 成功 false失败
*/
public boolean hset(String key,String item,Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
-
向一张hash表中放入数据,如果不存在将创建
-
@param key 键
-
@param item 项
-
@param value 值
-
@param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
-
@return true 成功 false失败
*/
public boolean hset(String key,String item,Object value,long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
-
删除hash表中的值
-
@param key 键 不能为null
-
@param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object… item){
redisTemplate.opsForHash().delete(key,item);
}
/**
-
判断hash表中是否有该项的值
-
@param key 键 不能为null
-
@param item 项 不能为null
-
@return true 存在 false不存在
*/
public boolean hHasKey(String key, String item){
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
-
hash递增 如果不存在,就会创建一个 并把新增后的值返回
-
@param key 键
-
@param item 项
-
@param by 要增加几(大于0)
-
@return
*/
public double hincr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
-
hash递减
-
@param key 键
-
@param item 项
-
@param by 要减少记(小于0)
-
@return
*/
public double hdecr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item,-by);
}
//set=
/**
-
根据key获取Set中的所有值
-
@param key 键
-
@return
*/
public Set sGet(String key){
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
-
根据value从一个set中查询,是否存在
-
@param key 键
-
@param value 值
-
@return true 存在 false不存在
*/
public boolean sHasKey(String key,Object value){
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
-
将数据放入set缓存
-
@param key 键
-
@param values 值 可以是多个
-
@return 成功个数
*/
public long sSet(String key, Object…values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
-
将set数据放入缓存
-
@param key 键
小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Java工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年最新Java开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Java)
public Set sGet(String key){
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
-
根据value从一个set中查询,是否存在
-
@param key 键
-
@param value 值
-
@return true 存在 false不存在
*/
public boolean sHasKey(String key,Object value){
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
-
将数据放入set缓存
-
@param key 键
-
@param values 值 可以是多个
-
@return 成功个数
*/
public long sSet(String key, Object…values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
-
将set数据放入缓存
-
@param key 键
小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Java工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年最新Java开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-graP05I6-1710935055545)]
[外链图片转存中…(img-rhHCkxMS-1710935055546)]
[外链图片转存中…(img-IlbFToek-1710935055546)]
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Java)
[外链图片转存中…(img-2rv7VOqZ-1710935055546)]