Commit d848b58f by 陈文顺

haha

parent d2847177
...@@ -6,13 +6,5 @@ package com.freemud.demo.dto; ...@@ -6,13 +6,5 @@ package com.freemud.demo.dto;
public class BaseRequest { public class BaseRequest {
private String companyId;
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
} }
...@@ -15,7 +15,7 @@ import java.util.List; ...@@ -15,7 +15,7 @@ import java.util.List;
* @author chenwenshun * @author chenwenshun
* *
*/ */
public class DictTypeDto implements Serializable{ public class DictTypeDto extends BaseRequest implements Serializable{
private static final long serialVersionUID = 2797285843251217167L; private static final long serialVersionUID = 2797285843251217167L;
@JSONField(serializeUsing = ToStringSerializer.class) @JSONField(serializeUsing = ToStringSerializer.class)
private Long id; private Long id;
......
...@@ -80,8 +80,9 @@ public class DictTypeServiceImpl implements IDictTypeService{ ...@@ -80,8 +80,9 @@ public class DictTypeServiceImpl implements IDictTypeService{
BeanUtils.copyProperties(dto,dictTypeEntity); BeanUtils.copyProperties(dto,dictTypeEntity);
dictTypeEntity.setCreatedDate(new Date()); dictTypeEntity.setCreatedDate(new Date());
dictTypeEntity.setUpdatedDate(new Date()); dictTypeEntity.setUpdatedDate(new Date());
this.dictTypeMapper.insertUseGeneratedKeys(dictTypeEntity); dictTypeEntity.setId(null);
// int r = this.dictTypeMapper.insertSelective(dictTypeEntity); // this.dictTypeMapper.insertUseGeneratedKeys(dictTypeEntity);
int r = this.dictTypeMapper.insertSelective(dictTypeEntity);
if (dto.getDictDataDtos()==null || dto.getDictDataDtos().isEmpty()){ if (dto.getDictDataDtos()==null || dto.getDictDataDtos().isEmpty()){
return; return;
} }
...@@ -100,6 +101,9 @@ public class DictTypeServiceImpl implements IDictTypeService{ ...@@ -100,6 +101,9 @@ public class DictTypeServiceImpl implements IDictTypeService{
@Override @Override
public void edit(DictTypeDto dto){ public void edit(DictTypeDto dto){
dictRedisCache.delCache(dto.getId());
dictRedisHashCache.delCache(dto.getDictTypeCd());
TDictType dictType = this.dictTypeMapper.selectByPrimaryKey(dto.getId()); TDictType dictType = this.dictTypeMapper.selectByPrimaryKey(dto.getId());
BeanUtils.copyProperties(dto,dictType); BeanUtils.copyProperties(dto,dictType);
dictType.setUpdatedDate(new Date()); dictType.setUpdatedDate(new Date());
...@@ -122,8 +126,7 @@ public class DictTypeServiceImpl implements IDictTypeService{ ...@@ -122,8 +126,7 @@ public class DictTypeServiceImpl implements IDictTypeService{
.collect(Collectors.toList()); .collect(Collectors.toList());
this.dictDataMapper.insertList(dictDataList); this.dictDataMapper.insertList(dictDataList);
dictRedisCache.delCache(dto.getId());
dictRedisHashCache.delCache(dto.getDictTypeCd());
...@@ -217,7 +220,7 @@ public class DictTypeServiceImpl implements IDictTypeService{ ...@@ -217,7 +220,7 @@ public class DictTypeServiceImpl implements IDictTypeService{
// } // }
Map<String,DictDataDto> map = dictRedisHashCache.getAllValue(dictTypeCd); Map<String,DictDataDto> map = dictRedisHashCache.getAllValue(dictTypeCd);
if (map == null){ if (map == null ){
return dictDataDtos; return dictDataDtos;
} }
......
...@@ -37,21 +37,26 @@ public abstract class RedisCache<T> { ...@@ -37,21 +37,26 @@ public abstract class RedisCache<T> {
*/ */
public T getCache(Object key){ public T getCache(Object key){
String redisKey = getRedisKey( key); String redisKey = getRedisKey( key);
T value = (T)redisTemplate.opsForValue().get(redisKey); Object value = redisTemplate.opsForValue().get(redisKey);
if (value != null){
return value; if ( value != null && !"".equals(value) ){
return (T)value;
}
if ( "".equals(value) ){
return null;
} }
value = searchDB(key); value = searchDB(key);
if (value == null){ if (value == null){
redisTemplate.opsForValue().set(redisKey, "",5, TimeUnit.MINUTES); redisTemplate.opsForValue().set(redisKey, "",5, TimeUnit.MINUTES);
}else { }else {
redisTemplate.opsForValue().set( redisKey,value, getExpire(), TimeUnit.HOURS); redisTemplate.opsForValue().set( redisKey,value, getExpire(), TimeUnit.HOURS);
} }
return value; return (T)value;
} }
/** /**
......
...@@ -44,7 +44,7 @@ public abstract class RedisHashCache<T> { ...@@ -44,7 +44,7 @@ public abstract class RedisHashCache<T> {
Map map = this.searchDB(key); Map map = this.searchDB(key);
if (map == null || map.size() == 0){ if (map == null || map.size() == 0){
redisTemplate.boundHashOps(getRedisKey(key)).put("",""); redisTemplate.boundHashOps(getRedisKey(key)).put(filed,"");
}else { }else {
......
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
</if> </if>
</where> </where>
order by id desc
</select> </select>
</mapper> </mapper>
\ No newline at end of file
...@@ -7,12 +7,15 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; ...@@ -7,12 +7,15 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication @SpringBootApplication
@ComponentScan(basePackages = "com.freemud, cn.freemud") @ComponentScan(basePackages = "com.freemud, cn.freemud")
@MapperScan(basePackages = "com.freemud.demo.mapper") @MapperScan(basePackages = "com.freemud.demo.mapper")
//@EnableEurekaClient //@EnableEurekaClient
public class SpringbootDemoApplication { public class SpringbootDemoApplication extends WebMvcConfigurerAdapter{
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args); SpringApplication.run(SpringbootDemoApplication.class, args);
...@@ -24,4 +27,12 @@ public class SpringbootDemoApplication { ...@@ -24,4 +27,12 @@ public class SpringbootDemoApplication {
} }
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
.maxAge(3600);
}
} }
package com.freemud.springbootdemo.aspect;
import com.freemud.demo.dto.BaseRequest;
import com.freemud.springbootdemo.config.DataSourceEnum;
import com.freemud.springbootdemo.config.DataSourceMapping;
import com.freemud.springbootdemo.config.RoutingDataSourceContextHolder;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.javassist.*;
import org.apache.ibatis.javassist.bytecode.CodeAttribute;
import org.apache.ibatis.javassist.bytecode.LocalVariableAttribute;
import org.apache.ibatis.javassist.bytecode.MethodInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by chenwenshun on 2018/12/12.
*/
@Aspect
@Component
public class RoutingDataSourceAspect {
@Autowired
private DataSourceMapping dataSourceMapping;
@Pointcut("execution(public * com.freemud.springbootdemo.controller.*.*(..))")
public void point() {
}
@Before("point()")
public void doBefore(JoinPoint joinPoint) throws ClassNotFoundException, NotFoundException {
String classType = joinPoint.getTarget().getClass().getName();
// Class<?> clazz = Class.forName(classType);
// String clazzName = clazz.getName();
String methodName = joinPoint.getSignature().getName(); //获取方法名称
Object[] args = joinPoint.getArgs();//参数
Map<String,Object> nameAndArgs = this.getFieldsName(this.getClass(),classType,methodName,args);
String companyId = null;
if (nameAndArgs.containsKey("companyId")){
companyId = (String)nameAndArgs.get("companyId");
}else if (nameAndArgs.containsKey("requestBody")){
BaseRequest request = (BaseRequest)nameAndArgs.get("requestBody");
companyId = request.getCompanyId();
}else {
BaseRequest request = (BaseRequest)Lists.newArrayList(nameAndArgs.values()).get(0);
companyId = request.getCompanyId();
}
if (StringUtils.isBlank(companyId)){
throw new UnsupportedOperationException("companyId can not be null!");
}
String ds = DataSourceEnum.DS_1.name();
if (dataSourceMapping != null){
ds = dataSourceMapping.getDataSource(Lists.newArrayList(DataSourceEnum.values()) ,"datasource_company_map_"+ companyId) ;
}
RoutingDataSourceContextHolder.set(DataSourceEnum.valueOf(ds));
}
@After("point()")
public void doAfter(){
RoutingDataSourceContextHolder.clear();
}
private Map<String,Object> getFieldsName(Class cls, String clazzName, String methodName, Object[] args) throws NotFoundException {
Map<String,Object > map=new LinkedHashMap<>();
ClassPool pool = ClassPool.getDefault();
ClassClassPath classPath = new ClassClassPath(cls);
pool.insertClassPath(classPath);
CtClass cc = pool.get(clazzName);
CtMethod cm = cc.getDeclaredMethod(methodName);
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < cm.getParameterTypes().length; i++){
map.put( attr.variableName(i + pos),args[i]);//paramNames即参数名
}
return map;
}
}
...@@ -21,37 +21,16 @@ import java.util.Map; ...@@ -21,37 +21,16 @@ import java.util.Map;
public class DataSourceConfig { public class DataSourceConfig {
@Bean @Bean
@Primary
@ConfigurationProperties(prefix = "datasource.druid") @ConfigurationProperties(prefix = "datasource.druid")
public DataSource dataSource1(){ public DataSource dataSource_0(){
return DataSourceBuilder.create() return DataSourceBuilder.create()
.type(DruidDataSource.class) .type(DruidDataSource.class)
.build(); .build();
} }
@Bean
@ConfigurationProperties(prefix = "datasource2.druid")
public DataSource dataSource2(){
return DataSourceBuilder.create()
.type(DruidDataSource.class)
.build();
}
@Bean
@Primary
public DataSource RoutingDataSource(
@Autowired @Qualifier("dataSource1") DataSource dataSource,
@Autowired @Qualifier("dataSource2") DataSource dataSource2
){
Map<Object, Object> map = new HashMap<>();
map.put(DataSourceEnum.DS_1, dataSource);
map.put(DataSourceEnum.DS_2, dataSource2);
RoutingDataSource routingDataSource = new RoutingDataSource();
routingDataSource.setTargetDataSources(map);
routingDataSource.setDefaultTargetDataSource(dataSource);
return routingDataSource;
}
......
package com.freemud.springbootdemo.config;
/**
* Created by chenwenshun on 2018/12/14.
* 多数据源编号
*/
public enum DataSourceEnum {
DS_1,
DS_2
}
package com.freemud.springbootdemo.config;
import java.util.Collection;
import java.util.List;
/**
* Created by chenwenshun on 2018/12/14.
* 商户与数据源的映射关系
* 具体项目不用实现
* 如:用数据库配置或者apollo,等方式
*/
public interface DataSourceMapping {
/**
* 商户ID 返回对应的数据源,可以采取两种方式
*
* 1、通过具体的配置
*
* 2、通过自己实现路由算法返回对应的数据源
* @param availableDataSources
* @param companyId
* @return
*/
String getDataSource(List<DataSourceEnum> availableDataSources, String companyId);
}
package com.freemud.springbootdemo.config;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.List;
/**
* Created by chenwenshun on 2018/12/14.
*/
@Component
public class DataSourceMappingImpl implements DataSourceMapping {
@ApolloConfig
private Config config;
@Override
public String getDataSource(List<DataSourceEnum> availableDataSources, String companyId) {
return config.getProperty(companyId, DataSourceEnum.DS_1.name());
}
}
package com.freemud.springbootdemo.config;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* Created by chenwenshun on 2018/12/12.
*/
public class RoutingDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
return RoutingDataSourceContextHolder.get();
}
}
package com.freemud.springbootdemo.config;
/**
* Created by chenwenshun on 2018/12/12.
*/
public class RoutingDataSourceContextHolder {
private static final ThreadLocal<DataSourceEnum> threadlocalDataSourceKey = new ThreadLocal<>();
public static void set(DataSourceEnum key){
threadlocalDataSourceKey.set(key);
}
public static DataSourceEnum get(){
return threadlocalDataSourceKey.get();
}
public static void clear() {
threadlocalDataSourceKey.remove();
}
}
package com.freemud.springbootdemo.controller; package com.freemud.springbootdemo.controller;
import com.freemud.demo.cache.DictRedisCache;
import com.freemud.demo.dto.*; import com.freemud.demo.dto.*;
import com.freemud.demo.service.IDictTypeService; import com.freemud.demo.service.IDictTypeService;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
...@@ -19,6 +20,9 @@ public class DictController { ...@@ -19,6 +20,9 @@ public class DictController {
@Autowired @Autowired
IDictTypeService dictTypeService; IDictTypeService dictTypeService;
@Autowired
DictRedisCache dictRedisCache;
@ApiOperation("分页查询列表") @ApiOperation("分页查询列表")
@PostMapping("/page") @PostMapping("/page")
public ResDto page(@RequestBody PageReq pageReq){ public ResDto page(@RequestBody PageReq pageReq){
...@@ -28,6 +32,14 @@ public class DictController { ...@@ -28,6 +32,14 @@ public class DictController {
} }
@GetMapping("/getById")
public ResDto getById(@RequestParam("id") Long id){
DictTypeDto dictTypeDto = dictRedisCache.getCache(id);
return new ResDto(dictTypeDto);
}
@ApiOperation("typeCd获取字典数据") @ApiOperation("typeCd获取字典数据")
@GetMapping( value = "/dictDatas/{dictTypeCd}") @GetMapping( value = "/dictDatas/{dictTypeCd}")
public ResDto dictDatas(@PathVariable String dictTypeCd){ public ResDto dictDatas(@PathVariable String dictTypeCd){
...@@ -68,7 +80,7 @@ public class DictController { ...@@ -68,7 +80,7 @@ public class DictController {
@GetMapping("/delete") @GetMapping("/delete")
public ResDto delete(Long dictTypeId,String companyId){ public ResDto delete(Long dictTypeId){
this.dictTypeService.deleteDict(dictTypeId); this.dictTypeService.deleteDict(dictTypeId);
return new ResDto(); return new ResDto();
} }
......
...@@ -24,7 +24,7 @@ datasource: ...@@ -24,7 +24,7 @@ datasource:
datasource2: datasource2:
druid: druid:
url: jdbc:mysql://111.231.82.13:6630/dict?useUnicode=true&characterEncoding=utf8 url: jdbc:mysql://111.231.82.13:6630/dict2?useUnicode=true&characterEncoding=utf8
driver-class: com.mysql.jdbc.Driver driver-class: com.mysql.jdbc.Driver
username: yanfa username: yanfa
password: yqKjKHX.1:bv password: yqKjKHX.1:bv
...@@ -46,7 +46,7 @@ mapper: ...@@ -46,7 +46,7 @@ mapper:
mappers: com.freemud.demo.util.MyMapper mappers: com.freemud.demo.util.MyMapper
not-empty: false not-empty: false
identity: MYSQL identity: MYSQL
before: true # before: true
#pagehelper #pagehelper
pagehelper: pagehelper:
...@@ -72,13 +72,13 @@ swagger_enable: true ...@@ -72,13 +72,13 @@ swagger_enable: true
# service-url: # service-url:
# defaultZone: http://localhost:10001/eureka # defaultZone: http://localhost:10001/eureka
apollo: #apollo:
bootstrap: # bootstrap:
enabled: true # enabled: true
meta: http://localhost:8080 # meta: http://localhost:8080
#apollo appId #apollo appId
app: #app:
id: order_service # id: order_service
...@@ -11,6 +11,8 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -11,6 +11,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import java.util.Random;
/** /**
* Created by chenwenshun on 2018/11/2. * Created by chenwenshun on 2018/11/2.
*/ */
...@@ -28,4 +30,13 @@ public class ServiceTest { ...@@ -28,4 +30,13 @@ public class ServiceTest {
PageData<DictTypeDto> page = dictTypeService.findPageDict(pageReq); PageData<DictTypeDto> page = dictTypeService.findPageDict(pageReq);
} }
@Test
public void testSave(){
Random random = new Random();
DictTypeDto dictTypeDto = new DictTypeDto();
dictTypeDto.setDictTypeCd("chenwstest1224"+random.nextInt(1000));
dictTypeDto.setDictTypeName("hahahadsfe");
dictTypeService.saveDict(dictTypeDto);
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment