authorization

master
bseayin 2019-09-15 21:33:38 +08:00
parent 02648370b9
commit a76d4d728b
13 changed files with 816 additions and 0 deletions

View File

@ -0,0 +1,15 @@
package com.zz;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
@MapperScan("com.zz.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}

View File

@ -0,0 +1,83 @@
package com.zz.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
// 自定义缓存key生成策略
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
StringBuffer sb = new StringBuffer();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
// 缓存管理器
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
@Bean
@SuppressWarnings({"rawtypes", "unchecked"})
public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory connectionFactory){
RedisTemplate<Object,Object> redisTemplate=new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
//使用Jackson2JsonRedisSerializer替换默认的序列化规则
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper=new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//设置value的序列化规则
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
//设置key的序列化规则
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
// private void setSerializer(StringRedisTemplate template) {
// @SuppressWarnings({ "rawtypes", "unchecked" })
// Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
// ObjectMapper om = new ObjectMapper();
// om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// jackson2JsonRedisSerializer.setObjectMapper(om);
// template.setValueSerializer(jackson2JsonRedisSerializer);
// }
}

View File

@ -0,0 +1,40 @@
package com.zz.controller;
import com.zz.entity.Computer;
import com.zz.service.ComputerService;
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.RestController;
import javax.annotation.Resource;
@RestController
public class ComputerController {
@Resource
ComputerService computerService;
@GetMapping("/get/{id}")
public Computer getComputer(@PathVariable("id") Long id) {
System.out.println("*******getComputer***" + id);
return computerService.selectByPrimaryKey(id);
}
@GetMapping("/del/{id}")
public int delComputer(@PathVariable("id") Long id) {
System.out.println("*******delComputer***" + id);
return computerService.deleteByPrimaryKey(id);
}
@GetMapping("/update/{id}/{name}")
public Computer updateComputer(@PathVariable("id") Long id, @PathVariable("name") String name) {
System.out.println("*******getComputer***" + id);
Computer computer = new Computer();
computer.setId(id);
computer.setName(name);
return computerService.updateByPrimaryKeySelective(computer);
}
@PostMapping("/updatecomputer")
public Computer updateComputer2(Computer computer) {
System.out.println("*******getComputer***" + computer.getName());
return computerService.updateByPrimaryKeySelective(computer);
}
}

View File

@ -0,0 +1,35 @@
package com.zz.entity;
import java.io.Serializable;
public class Computer implements Serializable {
private Long id;
private String name;
private Double price;
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 == null ? null : name.trim();
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}

View File

@ -0,0 +1,103 @@
package com.zz.entity;
public class User {
private Integer id;
private String name;
private String pwd;
private Integer age;
private String sex;
private String email;
private String mobile;
private Long productId;
private String password;
private String username;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd == null ? null : pwd.trim();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile == null ? null : mobile.trim();
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
}

View File

@ -0,0 +1,19 @@
package com.zz.mapper;
import com.zz.entity.Computer;
import org.springframework.cache.annotation.CacheConfig;
@CacheConfig(cacheNames = "computer")
public interface ComputerMapper {
int deleteByPrimaryKey(Long id);
int insert(Computer record);
int insertSelective(Computer record);
Computer selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(Computer record);
int updateByPrimaryKey(Computer record);
}

View File

@ -0,0 +1,17 @@
package com.zz.mapper;
import com.zz.entity.User;
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}

View File

@ -0,0 +1,119 @@
package com.zz.service;
import com.zz.entity.Computer;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
//@CacheConfig(cacheNames = "computer")
public interface ComputerService {
// @CacheEvict(key = "#p0", allEntries = true)
int deleteByPrimaryKey(Long id);
int insert(Computer record);
int insertSelective(Computer record);
// @Cacheable(key = "#p0")
Computer selectByPrimaryKey(Long id);
@CachePut(key = "#p0.id")
Computer updateByPrimaryKeySelective(Computer record);
int updateByPrimaryKey(Computer record);
}
/**
*
* 1
* SpringSpring Cache@Cacheable@CacheEvict使@CacheableSpring Cache使@CacheEvictSpring CacheSpringCache
*
* 1.1 @Cacheable
* @CacheableSpringSpringSpring@Cacheablevaluekeycondition
*
* 1.1.1 valueCache
* valueCacheCacheCacheCacheCache
*
* @Cacheable("cache1")//Cache是发生在cache1上的
*
* public User find(Integer id) {
*
* returnnull;
*
* }
*
*
*
* @Cacheable({"cache1", "cache2"})//Cache是发生在cache1和cache2上的
*
* public User find(Integer id) {
*
* returnnull;
*
* }
*
*
*
* 1.1.2 使keykey
* keySpringkeySpringELSpring使key
*
* SpringELkeyEL使使使##pindex使key
*
* @Cacheable(value="users", key="#id")
*
* public User find(Integer id) {
*
* returnnull;
*
* }
*
*
*
* @Cacheable(value="users", key="#p0")
*
* public User find(Integer id) {
*
* returnnull;
*
* }
*
*
*
* @Cacheable(value="users", key="#user.id")
*
* public User find(User user) {
*
* returnnull;
*
* }
* 1.2 @CachePut
* Spring Cache使@CacheableSpringCachekey@CachePut@Cacheable使@CachePut
*
* @CachePut使@CachePut@Cacheable
*
* @CachePut("users")//每次都会执行方法,并将结果存入指定的缓存中
*
* public User find(Integer id) {
*
* returnnull;
*
* }
*
*
*
* 1.3 @CacheEvict
* @CacheEvict@CacheEvictvaluekeyconditionallEntriesbeforeInvocationvaluekeycondition@CacheablevalueCacheCachekeykey使keyconditionallEntriesbeforeInvocation
*
* 1.3.1 allEntries
* allEntriesbooleanfalseallEntriestrueSpring CachekeyCache
*
* @CacheEvict(value="users", allEntries=true)
*
* public void delete(Integer id) {
*
* System.out.println("delete user by id: " + id);
*
* }
*
*
*
*
*/

View File

@ -0,0 +1,83 @@
package com.zz.service;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class RedisTemplateService {
@Autowired
StringRedisTemplate stringRedisTemplate;
public <T> boolean set(String key ,T value){
try {
//任意类型转换成String
String val = beanToString(value);
if(val==null||val.length()<=0){
return false;
}
stringRedisTemplate.opsForValue().set(key,val);
return true;
}catch (Exception e){
return false;
}
}
public <T> T get(String key,Class<T> clazz){
try {
String value = stringRedisTemplate.opsForValue().get(key);
return stringToBean(value,clazz);
}catch (Exception e){
return null ;
}
}
@SuppressWarnings("unchecked")
private <T> T stringToBean(String value, Class<T> clazz) {
if(value==null||value.length()<=0||clazz==null){
return null;
}
if(clazz ==int.class ||clazz==Integer.class){
return (T)Integer.valueOf(value);
}
else if(clazz==long.class||clazz==Long.class){
return (T)Long.valueOf(value);
}
else if(clazz==String.class){
return (T)value;
}else {
return JSON.toJavaObject(JSON.parseObject(value),clazz);
}
}
/**
*
* @return String
*/
private <T> String beanToString(T value) {
if(value==null){
return null;
}
Class <?> clazz = value.getClass();
if(clazz==int.class||clazz==Integer.class){
return ""+value;
}
else if(clazz==long.class||clazz==Long.class){
return ""+value;
}
else if(clazz==String.class){
return (String)value;
}else {
return JSON.toJSONString(value);
}
}
}

View File

@ -0,0 +1,52 @@
package com.zz.service.impl;
import com.zz.entity.Computer;
import com.zz.mapper.ComputerMapper;
import com.zz.service.ComputerService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
@CacheConfig(cacheNames = "computer")
public class ComputerServiceImpl implements ComputerService {
@Resource
ComputerMapper computerMapper;
@Override
@CacheEvict(key = "#p0.toString()", allEntries = true)
public int deleteByPrimaryKey(Long id) {
return 0;
}
@Override
public int insert(Computer record) {
return 0;
}
@Override
public int insertSelective(Computer record) {
return 0;
}
@Override
@Cacheable(key = "#p0.toString()")
public Computer selectByPrimaryKey(Long id) {
return computerMapper.selectByPrimaryKey(id);
}
@Override
@CachePut(key = "#p0.id.toString()")
public Computer updateByPrimaryKeySelective(Computer record) {
computerMapper.updateByPrimaryKeySelective(record);
return computerMapper.selectByPrimaryKey(record.getId());
}
@Override
public int updateByPrimaryKey(Computer record) {
return 0;
}
}

View File

@ -0,0 +1,27 @@
#Redis
#spring.redis.host=127.0.0.1
redis.host=127.0.0.1
## Redis服务器连接端口
redis.port=6379
## 连接超时时间(毫秒)
redis.timeout=3
## Redis服务器连接密码默认为空
#redis.password=135246
## 连接池中的最大连接数
redis.poolMaxTotal=10
## 连接池中的最大空闲连接
redis.poolMaxIdle=10
## 连接池最大阻塞等待时间(使用负值表示没有限制)
redis.poolMaxWait=3
## Mybatis 配置
spring.datasource.url = jdbc:mysql://localhost:3306/java10?useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username = root
spring.datasource.password = Java20190713*yy
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
mybatis.typeAliasesPackage=org.spring.springboot.domain
#mybatis.mapperLocations=classpath:com/zz/mapping/*.xml,com/zz/EDGE/mapping/*.xml,com/zz/jwh/mapping/*.xml,com/zz/hc/mapping/*.xml,com/zz/simpleSpade/mapping/*.xml,com/zz/lsw/mapping/*.xml,com/zz/wsq/mapping/*.xml,com/zz/zcj/mapping/*.xml
mybatis.mapperLocations=classpath:mapping/*.xml
logging.level.com.zz.mapper=DEBUG

View File

@ -0,0 +1,71 @@
<?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.zz.mapper.ComputerMapper">
<resultMap id="BaseResultMap" type="com.zz.entity.Computer">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="price" jdbcType="DOUBLE" property="price" />
</resultMap>
<sql id="Base_Column_List">
id, name, price
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from computer
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from computer
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.zz.entity.Computer">
insert into computer (id, name, price
)
values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{price,jdbcType=DOUBLE}
)
</insert>
<insert id="insertSelective" parameterType="com.zz.entity.Computer">
insert into computer
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="price != null">
price,
</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="price != null">
#{price,jdbcType=DOUBLE},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.zz.entity.Computer">
update computer
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="price != null">
price = #{price,jdbcType=DOUBLE},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.zz.entity.Computer">
update computer
set name = #{name,jdbcType=VARCHAR},
price = #{price,jdbcType=DOUBLE}
where id = #{id,jdbcType=BIGINT}
</update>
</mapper>

View File

@ -0,0 +1,152 @@
<?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.zz.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.zz.entity.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="pwd" jdbcType="VARCHAR" property="pwd" />
<result column="age" jdbcType="INTEGER" property="age" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="mobile" jdbcType="VARCHAR" property="mobile" />
<result column="product_id" jdbcType="BIGINT" property="productId" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="username" jdbcType="VARCHAR" property="username" />
</resultMap>
<sql id="Base_Column_List">
id, name, pwd, age, sex, email, mobile, product_id, password, username
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.zz.entity.User">
insert into user (id, name, pwd,
age, sex, email, mobile,
product_id, password, username
)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{pwd,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER}, #{sex,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, #{mobile,jdbcType=VARCHAR},
#{productId,jdbcType=BIGINT}, #{password,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.zz.entity.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="pwd != null">
pwd,
</if>
<if test="age != null">
age,
</if>
<if test="sex != null">
sex,
</if>
<if test="email != null">
email,
</if>
<if test="mobile != null">
mobile,
</if>
<if test="productId != null">
product_id,
</if>
<if test="password != null">
password,
</if>
<if test="username != null">
username,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="pwd != null">
#{pwd,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
<if test="sex != null">
#{sex,jdbcType=VARCHAR},
</if>
<if test="email != null">
#{email,jdbcType=VARCHAR},
</if>
<if test="mobile != null">
#{mobile,jdbcType=VARCHAR},
</if>
<if test="productId != null">
#{productId,jdbcType=BIGINT},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.zz.entity.User">
update user
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="pwd != null">
pwd = #{pwd,jdbcType=VARCHAR},
</if>
<if test="age != null">
age = #{age,jdbcType=INTEGER},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="email != null">
email = #{email,jdbcType=VARCHAR},
</if>
<if test="mobile != null">
mobile = #{mobile,jdbcType=VARCHAR},
</if>
<if test="productId != null">
product_id = #{productId,jdbcType=BIGINT},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="username != null">
username = #{username,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.zz.entity.User">
update user
set name = #{name,jdbcType=VARCHAR},
pwd = #{pwd,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
sex = #{sex,jdbcType=VARCHAR},
email = #{email,jdbcType=VARCHAR},
mobile = #{mobile,jdbcType=VARCHAR},
product_id = #{productId,jdbcType=BIGINT},
password = #{password,jdbcType=VARCHAR},
username = #{username,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>